Python语言程序设计Y.Daniel Liang练习题Chapter9.2

ckp9.21-9.23

'''
ckp9.21
LEFT需要和side一块使用,LEFT是side的属性值,如果直接使用pack(LEFT)那么就会报错
出现 AttributeError: 'str' object has no attribute 'items'

ckp9.22
THe Pack Manager

ckp9.23
The place manager is not compatible with all computers. If you run this program on
Windows with a screen monitor with resolution, the layout size is just right.
When the program is run on Windows with a monitor with a higher resolution, the
components appear very small and clump together. When it is run on Windows with a
monitor with a lower resolution, they cannot be shown in their entirety. Because of these
incompatibility issues, you should generally avoid using the place manager.

'''

ckp9.25-9.27

'''
ckp9.25
The image file must be in GIF format. You can use a conversion utility to convert image
files in other formats into GIF format.

ckp9.26
引号里的是file的属性值。需要注明 file = "image/us.gif",而不是直接给出地址。

ckp9.27
caImage = PhotoImage(file = "c:\pybook\image\canada.gif")
frame = Frame(window)
frame.pack()
Button(frame, image = caImage).pack()

'''

ckp9.30-9.36

'''

ckp9.30
canvas.bind("<Button-1>", p)

ckp9.31
<Button-3>

ckp9.32
<Double-Button-1>

ckp9.33
<Triple-Button-2>

ckp9.34
每个处理程序都有一个事件作为其参数

ckp9.35
用 x and y两个参数

ckp9.36
用 char 参数

'''

ckp9.37-9.38

'''
ckp9.37
    def stop(self): # Stop animation
        self.isStopped = True

ckp9.38
    def resume(self): # Resume animation
        self.isStopped = False
        self.animate()

'''

list9.7

from tkinter import * # Import all definitions from tkinter

class GridManagerDemo:
    window = Tk() # Create a window
    window.title("Grid Manager Demo") # Set title

    message = Message(window, text = "This Message widget occupies three rows and two columns")

    message.grid(row = 1, column = 1, rowspan = 3, columnspan = 2)
    Label(window, text = "First Name:").grid(row = 1, column = 3)
    Entry(window).grid(row = 1, column = 4, padx = 5, pady = 5)
    Label(window, text = "Last Name:").grid(row = 2, column = 3)
    Entry(window).grid(row = 2, column = 4)
    Button(window, text = "Get Name").grid(row = 3,
                                           padx = 5, pady = 5, column = 4, sticky = E)

    window.mainloop() # Create an event loop

GridManagerDemo() # Create GUI

 

 

list9.8

from tkinter import * # Import all definitions from tkinter

class PackManagerDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Pack Manager Demo 1") # Set title

        Label(window, text = "Blue", bg = "blue").pack()
        Label(window, text = "Red", bg = "red").pack(fill = BOTH, expand = 1)
        Label(window, text = "Green", bg = "green").pack(fill = BOTH)

        window.mainloop() # Create an event loop

PackManagerDemo() # Create GUI

 

 

list9.11

from tkinter import * # Import all definitions from tkinter

class LoanCalculator:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Loan Calculator") # Set title

        Label(window, text = "Annual Interest Rate").grid(row = 1,
                                                          column = 1, sticky = W)
        Label(window, text = "Number of Years").grid(row = 2,
                                                     column = 1, sticky = W)
        Label(window, text = "Loan Amount").grid(row = 3,
                                                 column = 1, sticky = W)
        Label(window, text = "Monthly Payment").grid(row = 4,
                                                     column = 1, sticky = W)
        Label(window, text = "Total Payment").grid(row = 5,
                                                   column = 1, sticky = W)

        self.annualInterestRateVar = StringVar()
        Entry(window, textvariable = self.annualInterestRateVar,
              justify = RIGHT).grid(row = 1, column = 2)
        self.numberOfYearsVar = StringVar()
        Entry(window, textvariable = self.numberOfYearsVar,
              justify = RIGHT).grid(row = 2, column = 2)
        self.loanAmountVar = StringVar()
        Entry(window, textvariable = self.loanAmountVar,
              justify = RIGHT).grid(row = 3, column = 2)

        self.monthlyPaymentVar = StringVar()
        lblMonthlyPayment = Label(window, textvariable =
            self.monthlyPaymentVar).grid(row = 4, column = 2,
                                     sticky = E)
        self.totalPaymentVar = StringVar()
        lblTotalPayment = Label(window, textvariable =
            self.totalPaymentVar).grid(row = 5,
                                   column = 2, sticky = E)
        btComputerPayment = Button(window, text = "Compute Payment",
                                   command = self.computerPayment).grid(
            row = 6, column = 2, sticky = E)

        window.mainloop() # Create an event loop
    def computerPayment(self):
        monthlyPayment = self.getMonthlyPayment(
            float(self.loanAmountVar.get()),
            float(self.annualInterestRateVar.get()) / 1200,
            int(self.numberOfYearsVar.get()))
        self.monthlyPaymentVar.set(format(monthlyPayment, "10.2f"))
        totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
                       * int(self.numberOfYearsVar.get())
        self.totalPaymentVar.set(format(totalPayment, "10.2f"))


    def getMonthlyPayment(self, loanAmount, monthlyInterestRate, numberOfYears):
        monthlyPayment = loanAmount * monthlyInterestRate / (1
                - 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
        return monthlyPayment;

LoanCalculator() # Create GUI

 

 

list9.12

from tkinter import * # Import all definitions from tkinter

class ImageDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Image Demo") # Set title

        # Create PhotoImage objects
        caImage = PhotoImage(file = "C:/pic/ca.gif")
        chinaImage = PhotoImage(file = "C:/pic/china.gif")
        leftImage = PhotoImage(file = "C:/pic/left.gif")
        rightImage = PhotoImage(file = "C:/pic/right.gif")
        usImage = PhotoImage(file = "C:/pic/usIcon.gif")
        ukImage = PhotoImage(file = "C:/pic/ukIcon.gif")
        crossImage = PhotoImage(file = "C:/pic/x.gif")
        circleImage = PhotoImage(file = "C:/pic/o.gif")

        # frame1 to contain label and canvas
        frame1 = Frame(window)
        frame1.pack()
        Label(frame1, image = caImage).pack(side = LEFT)
        canvas = Canvas(frame1)
        canvas.create_image(90, 50, image = chinaImage)
        canvas["width"] = 200
        canvas["height"] = 100
        canvas.pack(side = LEFT)

        # frame2 contains buttons, check buttons, and radio buttons
        frame2 = Frame(window)
        frame2.pack()
        Button(frame2, image = leftImage).pack(side = LEFT)
        Button(frame2, image = rightImage).pack(side = LEFT)
        Checkbutton(frame2, image = usImage).pack(side = LEFT)
        Checkbutton(frame2, image = ukImage).pack(side = LEFT)
        Radiobutton(frame2, image = crossImage).pack(side = LEFT)
        Radiobutton(frame2, image = circleImage).pack(side = LEFT)

        window.mainloop() # Create an event loop

ImageDemo() # Create GUI

 

 

list9.13

from tkinter import *

class MenuDemo:
    def __init__(self):
        window = Tk()
        window.title("Menu Demo")

        # Create a menu bar
        menubar = Menu(window)
        window.config(menu = menubar)# Display the menu bar

        # Create a pull-down menu, and add it to the menu bar
        operationMenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "Operation", menu = operationMenu)
        operationMenu.add_command(label = "Add", command = self.add)

        operationMenu.add_command(label = "Subtract",command = self.subtract)

        operationMenu.add_separator()
        operationMenu.add_command(label = "Multiply",command = self.multiply)

        operationMenu.add_command(label = "Divide",command = self.divide)


        # Create more pull-down menus
        exitmenu = Menu(menubar, tearoff = 0)
        menubar.add_cascade(label = "Exit", menu = exitmenu)
        exitmenu.add_command(label = "Quit", command = window.quit)

        # Add a tool bar frame
        frame0 = Frame(window) # Create and add a frame to window
        frame0.grid(row=1, column=1, sticky=W)

        # Create images
        plusImage = PhotoImage(file="C:/pic/plus.gif")
        minusImage = PhotoImage(file="C:/pic/minus.gif")
        timesImage = PhotoImage(file="C:/pic/times.gif")
        divideImage = PhotoImage(file="C:/pic/divide.gif")

        Button(frame0, image = plusImage, command =self.add).grid(row = 1, column = 1, sticky = W)

        Button(frame0, image = minusImage,command = self.subtract).grid(row = 1, column = 2)

        Button(frame0, image = timesImage,command = self.multiply).grid(row = 1, column = 3)

        Button(frame0, image = divideImage,command = self.divide).grid(row = 1, column = 4)


        # Add labels and entries to frame1
        frame1 = Frame(window)
        frame1.grid(row = 2, column = 1, pady = 10)
        Label(frame1, text = "Number 1:").pack(side = LEFT)
        self.v1 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v1,justify = RIGHT).pack(side = LEFT)

        Label(frame1, text = "Number 2:").pack(side = LEFT)
        self.v2 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v2,justify = RIGHT).pack(side = LEFT)

        Label(frame1, text = "Result:").pack(side = LEFT)
        self.v3 = StringVar()
        Entry(frame1, width = 5, textvariable = self.v3,justify = RIGHT).pack(side = LEFT)


        # Add buttons to frame2
        frame2 = Frame(window) # Create and add a frame to window
        frame2.grid(row = 3, column = 1, pady = 10, sticky = E)
        Button(frame2, text="Add", command=self.add).pack(side = LEFT)

        Button(frame2, text = "Subtract",command = self.subtract).pack(side = LEFT)

        Button(frame2, text = "Multiply",command = self.multiply).pack(side = LEFT)

        Button(frame2, text = "Divide",command = self.divide).pack(side = LEFT)


        mainloop()

    def add(self):
        self.v3.set(eval(self.v1.get()) + eval(self.v2.get()))

    def subtract(self):
        self.v3.set(eval(self.v1.get()) - eval(self.v2.get()))

    def multiply(self):
        self.v3.set(eval(self.v1.get()) * eval(self.v2.get()))

    def divide(self):
        self.v3.set(eval(self.v1.get()) / eval(self.v2.get()))

MenuDemo() # Create GUI

 

 

list9.15

from tkinter import * # Import all definitions from tkinter

class MouseKeyEventDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Event Demo") # Set a title
        canvas = Canvas(window, bg = "white", width = 200, height = 100)
        canvas.pack()

        # Bind with <Button-1> event
        canvas.bind("<Button-1>", self.processMouseEvent)

        # Bind with <Key> event
        canvas.bind("<Key>", self.processKeyEvent)
        canvas.focus_set()

        window.mainloop() # Create an event loop

    def processMouseEvent(self, event):
        print("clicked at", event.x, event.y)
        print("Position in the screen", event.x_root, event.y_root)
        print("Which button is clicked? ", event.num)

    def processKeyEvent(self, event):
        print("keysym? ", event.keysym)
        print("char? ", event.char)
        print("keycode? ", event.keycode)

MouseKeyEventDemo() # Create GUI

 

 

list9.16

from tkinter import * # Import all definitions from tkinter

class EnlargeShrinkCircle:
    def __init__(self):
        self.radius = 50

        window = Tk() # Create a window
        window.title("Control Circle Demo") # Set a title
        self.canvas = Canvas(window, bg = "white",
        width = 200, height = 200)
        self.canvas.pack()
        self.canvas.create_oval(100 - self.radius, 100 - self.radius,
                                100 + self.radius, 100 + self.radius, tags = "oval")


        # Bind canvas with mouse events
        self.canvas.bind("<Button-1>", self.increaseCircle)
        self.canvas.bind("<Button-3>", self.decreaseCircle)

        window.mainloop() # Create an event loop

    def increaseCircle(self, event):
        self.canvas.delete("oval")
        if self.radius < 100:
            self.radius += 2
        self.canvas.create_oval(100 - self.radius, 100 - self.radius,
                                100 + self.radius, 100 + self.radius, tags = "oval")


    def decreaseCircle(self, event):
        self.canvas.delete("oval")
        if self.radius > 2:
            self.radius -= 2
        self.canvas.create_oval(100 - self.radius, 100 - self.radius,
                                100 + self.radius, 100 + self.radius, tags = "oval")


EnlargeShrinkCircle() # Create GUI

 

 liat9.17

from tkinter import * # Import all definitions from tkinter

class AnimationDemo:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Animation Demo") # Set a title

        width = 250 # Width of the canvas
        canvas = Canvas(window, bg="white",width = 250, height = 50)

        canvas.pack()

        x = 0 # Starting x position
        canvas.create_text(x, 30,text = "Message moving?", tags = "text")


        dx = 3
        while True:
            canvas.after(100) # Move text dx unit
            canvas.move("text", dx, 0) # Sleep for 100 milliseconds
            canvas.update() # Update canvas
            if x < width:
                x += dx # Get the current position for string
            else:
                x = 0 # Reset string position to the beginning
                canvas.delete("text")
                # Redraw text at the beginning
                canvas.create_text(x, 30, text = "Message moving?",tags = "text")


        window.mainloop() # Create an event loop

AnimationDemo() # Create GUI

 

 

list9.18

from tkinter import * # Import all definitions from tkinter

class ControlAnimation:
    def __init__(self):
        window = Tk() # Create a window
        window.title("Control Animation Demo") # Set a title

        self.width = 250 # Width of self.canvas
        self.canvas = Canvas(window, bg = "white",width = self.width, height = 50)

        self.canvas.pack()

        frame = Frame(window)
        frame.pack()
        btStop = Button(frame, text = "Stop", command = self.stop)
        btStop.pack(side = LEFT)
        btResume = Button(frame, text = "Resume",command = self.resume)

        btResume.pack(side = LEFT)
        btFaster = Button(frame, text = "Faster",command = self.faster)

        btFaster.pack(side = LEFT)
        btSlower = Button(frame, text = "Slower",command = self.slower)

        btSlower.pack(side = LEFT)

        self.x = 0 # Starting x position
        self.sleepTime = 100 # Set a sleep time
        self.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text")


        self.dx = 3
        self.isStopped = False
        self.animate()

        window.mainloop() # Create an event loop

    def stop(self): # Stop animation
        self.isStopped = True

    def resume(self): # Resume animation
        self.isStopped = False
        self.animate()

    def faster(self): # Speed up the animation
        if self.sleepTime > 5:
            self.sleepTime -= 20

    def slower(self):# Slow down the animation
        self.sleepTime += 20

    def animate(self): # Move the message
        while not self.isStopped:
            self.canvas.move("text", self.dx, 0) # Move text
            self.canvas.after(self.sleepTime) # Sleep
            self.canvas.update() # Update canvas
            if self.x < self.width:
                self.x += self.dx # Set new position
            else:
                self.x = 0 # Reset string position to beginning
                self.canvas.delete("text")
                # Redraw text at the beginning
                self.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text")


ControlAnimation() # Create GUI

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值