当前位置: 代码迷 >> 综合 >> Python语言程序设计Y.Daniel Liang练习题Chapter9.2
  详细解决方案

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

热度:78   发布时间:2023-12-01 21:25:51.0

ckp9.21-9.23

'''
ckp9.21
LEFT需要和side一块使用,LEFT是side的属性值,如果直接使用pack(LEFT)那么就会报错
出现 AttributeError: 'str' object has no attribute 'items'ckp9.22
THe Pack Managerckp9.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.37def stop(self): # Stop animationself.isStopped = Trueckp9.38def resume(self): # Resume animationself.isStopped = Falseself.animate()'''

list9.7

from tkinter import * # Import all definitions from tkinterclass GridManagerDemo:window = Tk() # Create a windowwindow.title("Grid Manager Demo") # Set titlemessage = 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 loopGridManagerDemo() # Create GUI

 

 

list9.8

from tkinter import * # Import all definitions from tkinterclass PackManagerDemo:def __init__(self):window = Tk() # Create a windowwindow.title("Pack Manager Demo 1") # Set titleLabel(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 loopPackManagerDemo() # Create GUI

 

 

list9.11

from tkinter import * # Import all definitions from tkinterclass LoanCalculator:def __init__(self):window = Tk() # Create a windowwindow.title("Loan Calculator") # Set titleLabel(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 loopdef 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 tkinterclass ImageDemo:def __init__(self):window = Tk() # Create a windowwindow.title("Image Demo") # Set title# Create PhotoImage objectscaImage = 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 canvasframe1 = Frame(window)frame1.pack()Label(frame1, image = caImage).pack(side = LEFT)canvas = Canvas(frame1)canvas.create_image(90, 50, image = chinaImage)canvas["width"] = 200canvas["height"] = 100canvas.pack(side = LEFT)# frame2 contains buttons, check buttons, and radio buttonsframe2 = 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 loopImageDemo() # Create GUI

 

 

list9.13

from tkinter import *class MenuDemo:def __init__(self):window = Tk()window.title("Menu Demo")# Create a menu barmenubar = Menu(window)window.config(menu = menubar)# Display the menu bar# Create a pull-down menu, and add it to the menu baroperationMenu = 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 menusexitmenu = Menu(menubar, tearoff = 0)menubar.add_cascade(label = "Exit", menu = exitmenu)exitmenu.add_command(label = "Quit", command = window.quit)# Add a tool bar frameframe0 = Frame(window) # Create and add a frame to windowframe0.grid(row=1, column=1, sticky=W)# Create imagesplusImage = 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 frame1frame1 = 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 frame2frame2 = Frame(window) # Create and add a frame to windowframe2.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 tkinterclass MouseKeyEventDemo:def __init__(self):window = Tk() # Create a windowwindow.title("Event Demo") # Set a titlecanvas = Canvas(window, bg = "white", width = 200, height = 100)canvas.pack()# Bind with <Button-1> eventcanvas.bind("<Button-1>", self.processMouseEvent)# Bind with <Key> eventcanvas.bind("<Key>", self.processKeyEvent)canvas.focus_set()window.mainloop() # Create an event loopdef 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 tkinterclass EnlargeShrinkCircle:def __init__(self):self.radius = 50window = Tk() # Create a windowwindow.title("Control Circle Demo") # Set a titleself.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 eventsself.canvas.bind("<Button-1>", self.increaseCircle)self.canvas.bind("<Button-3>", self.decreaseCircle)window.mainloop() # Create an event loopdef increaseCircle(self, event):self.canvas.delete("oval")if self.radius < 100:self.radius += 2self.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 -= 2self.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 tkinterclass AnimationDemo:def __init__(self):window = Tk() # Create a windowwindow.title("Animation Demo") # Set a titlewidth = 250 # Width of the canvascanvas = Canvas(window, bg="white",width = 250, height = 50)canvas.pack()x = 0 # Starting x positioncanvas.create_text(x, 30,text = "Message moving?", tags = "text")dx = 3while True:canvas.after(100) # Move text dx unitcanvas.move("text", dx, 0) # Sleep for 100 millisecondscanvas.update() # Update canvasif x < width:x += dx # Get the current position for stringelse:x = 0 # Reset string position to the beginningcanvas.delete("text")# Redraw text at the beginningcanvas.create_text(x, 30, text = "Message moving?",tags = "text")window.mainloop() # Create an event loopAnimationDemo() # Create GUI

 

 

list9.18

from tkinter import * # Import all definitions from tkinterclass ControlAnimation:def __init__(self):window = Tk() # Create a windowwindow.title("Control Animation Demo") # Set a titleself.width = 250 # Width of self.canvasself.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 positionself.sleepTime = 100 # Set a sleep timeself.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text")self.dx = 3self.isStopped = Falseself.animate()window.mainloop() # Create an event loopdef stop(self): # Stop animationself.isStopped = Truedef resume(self): # Resume animationself.isStopped = Falseself.animate()def faster(self): # Speed up the animationif self.sleepTime > 5:self.sleepTime -= 20def slower(self):# Slow down the animationself.sleepTime += 20def animate(self): # Move the messagewhile not self.isStopped:self.canvas.move("text", self.dx, 0) # Move textself.canvas.after(self.sleepTime) # Sleepself.canvas.update() # Update canvasif self.x < self.width:self.x += self.dx # Set new positionelse:self.x = 0 # Reset string position to beginningself.canvas.delete("text")# Redraw text at the beginningself.canvas.create_text(self.x, 30, text = "Message moving?", tags = "text")ControlAnimation() # Create GUI