def get_image_path(): width, height = 300, 150 win = GraphWin("Image Path", width, height) win.setBackground(color_rgb(0, 0, 0)) path_entry = Entry(Point(width // 2, height // 2 - 50), 30) path_entry.draw(win) ok_button = Rectangle(Point(width - 50, height - 50), Point(width - 5, height - 5)) ok_button.setFill(color_rgb(255, 255, 255)) ok_button.draw(win) ok_button_text = Text(ok_button.getCenter(), "OK") ok_button_text.setSize(15) ok_button_text.draw(win) while True: click = win.getMouse() clickx = click.getX() clicky = click.getY() if ok_button.getP1().getX() <= clickx <= ok_button.getP2().getX( ) and ok_button.getP1().getY() <= clicky <= ok_button.getP2().getY(): win.close() return str(path_entry.getText())
def run(self): while self.money >= 10 and self.interface.wantToPlay(): self.playRound() scoreboard = Scoreboard() for score in scoreboard.top10: if self.money > int(score.score): win2 = GraphWin("Dice Poker", 600, 400) win2.setBackground("green3") banner = Text(Point(300, 30), "New High Score!\nPlease enter your name:") banner.setSize(24) banner.setFill("yellow2") banner.setStyle("bold") banner.draw(win2) textbox = Entry(Point(300, 150), 30) textbox.draw(win2) enter_btn = Button(win2, Point(300, 200), 60, 30, "Enter") enter_btn.activate() p = win2.getMouse() playerName = str(textbox.getText()) if enter_btn.clicked(p): scoreboard.addScore(playerName, self.money) scoreboard.sortScores() scoreboard.saveScores() break self.interface.close()
def ten_strings(): """ 7. Write a function, ten_strings(), that allows the user to plot 10 strings of their choice at locations of a graphics window chosen by clicking on the mouse (the strings should be entered one-by-one by the user within a text entry box at the top of the graphics window, clicking the mouse after entering each one). """ win = GraphWin("Ten strings", 400, 300) message = Text(Point(200, 15), "Enter what you want then click where you want it") message.draw(win) input_box = Entry(Point(200, 50), 10) input_box.draw(win) for _ in range(10): position = win.getMouse() if input_box.getText() == "": new_message = Text(position, "[EMPTY MESSAGE]") else: new_message = Text(position, input_box.getText()) new_message.draw(win) input_box.setText("") message.setText("You have used up all of your messages") await_user_input(win)
def __init__(self, canvas, point, input_type, label_text, char_max=10, default_val=None): allowed_types = ['unsigned_int', 'unsigned_float', 'float'] if input_type not in allowed_types: raise Exception('InputBox: type given is not an allowed type') self.canvas = canvas self.point = point self.type = input_type self.label = Text(point, label_text) x_offset = 120 + ((char_max - 10)/2.0 * 9) # diff b/t default char_max and font_size / 2 self.entry = Entry(Point(point.x + x_offset, point.y), char_max) if default_val is not None: self.set_input(default_val) self.draw()
def __init__(self, label, default, point, width, least, most): # Because it's monospace font face = 'courier' self.default = default self.min = least self.max = most self.entry = Entry(point, width) self.entry.setFace(face) self.entry.setText(default) # This only works because the font face is courier (monospace) # It more than double the label length, so that when it's center # matches that of the input, the text aligns perfectly on the left. self.label = Text(point, label + ': ' + (' ' * (6 + len(label)))) self.label.setFace('courier')
class InputBox(UIBase): def __init__(self, canvas, point, input_type, label_text, char_max=10, default_val=None): allowed_types = ['unsigned_int', 'unsigned_float', 'float'] if input_type not in allowed_types: raise Exception('InputBox: type given is not an allowed type') self.canvas = canvas self.point = point self.type = input_type self.label = Text(point, label_text) x_offset = 120 + ((char_max - 10)/2.0 * 9) # diff b/t default char_max and font_size / 2 self.entry = Entry(Point(point.x + x_offset, point.y), char_max) if default_val is not None: self.set_input(default_val) self.draw() @property def input_text(self): return self.entry.getText() def validate_input(self): flag = True if self.type == 'unsigned_int': flag = isinstance(int(self.input_text), int) and int(self.input_text) > 0 elif self.type == 'unsigned_float': flag = isinstance(float(self.input_text), float) and float(self.input_text) > 0 elif self.type == 'float': flag = isinstance(float(self.input_text), float) if not flag: self.label.setTextColor('red') else: self.label.setTextColor('black') return flag def set_input(self, val): self.entry.setText(val) if self.validate_input() is not True: self.entry.setText('') def draw(self): self.label.draw(self.canvas) self.entry.draw(self.canvas) def undraw(self): self.label.undraw() self.entry.undraw() def get_point_with_offset(self): return Point(self.point.x, self.point.y + 30)
class InputDialog: """ A custom window for getting simulation values (angle, velocity, and height) from the user.""" def __init__(self, angle, vel, height): """ Build and display the ingut window """ self.win = win = GraphWin("Initial Values", 200, 300) win.setCoords(0, 4.5, 4, 0.5) Text(Point(1, 1), "Angle").draw(win) self.angle = Entry(Point(3, 1), 5).draw(win) self.angle.setText(str(angle)) Text(Point(1, 2), "Velocity").draw(win) self.vel = Entry(Point(3, 2), 5).draw(win) self.vel.setText(str(vel)) Text(Point(1, 3), "Height").draw(win) self.height = Entry(Point(3, 3), 5).draw(win) self.height.setText(str(height)) self.fire = Button(win, Point(1, 4), 1.25, 0.5, "Fire!") self.fire.activate() self.quit = Button(win, Point(3, 4), 1.25, 0.5, "Quit") self.quit.activate() def interact(self): """ wait for user to click Quit or Fire button Returns a string indicating which button was clicked """ while True: pt = self.win.getMouse() if self.quit.clicked(pt): return "Quit" if self.fire.clicked(pt): return "Fire!" def getValues(self): """ return input values """ a = float(self.angle.getText()) v = float(self.vel.getText()) h = float(self.height.getText()) return a, v, h def close(self): """ close the input window """ self.win.close()
def make_text_with_input(x, y, col, size, text, init_value="", width=10): begin = 0 if col == 1: begin = 220 elif col == 2: begin = 580 elif col == 3: begin = 920 elif col == 4: begin = 1180 text = make_text(x, y, size, text) entry = Entry(Point(begin, y), width) entry.setFill("white") entry.setText(init_value if init_value != "None" else "") entry.draw(win) return entry, text
def plot_rainfall(): """ 10. [harder] Write a function, plot_rainfall(), that plots a histogram for daily rainfall figures over a 7 day period. The rainfall figures should be entered one-by-one into a text entry box within the window. The bars of the histogram should be numbered along the bottom. """ win = GraphWin("Plot Rainfall", 550, 300) message = Text(Point(275, 15), "Enter rainfall in mm over the last 7 days") message.draw(win) input_box = Entry(Point(275, 50), 10) input_box.draw(win) line1 = Line(Point(50, 70), Point(50, 260)) line2 = Line(Point(50, 260), Point(470, 260)) line1.draw(win) line2.draw(win) for i in range(7): text = Text(Point(70 + i * 60, 270), "Day " + str(i + 1)) text.draw(win) for i in range(6): text = Text(Point(30, 255 - i * 36), i * 40) text.draw(win) for i in range(7): win.getMouse() box_message = int(input_box.getText()) Rectangle(Point(50 + i * 60, 260 - box_message), Point(110 + i * 60, 260)).draw(win) message.setText("You're all finished") await_user_input(win)
class InputDialog(object): def __init__(self, angle, vel, height): self.win = win = GraphWin('Init', 200, 300) win.setCoords(0, 4.5, 4, 0.5) Text(Point(1, 1), 'angle: ').draw(win) self.angle = Entry(Point(3, 1), 5).draw(win) self.angle.setText(str(angle)) Text(Point(1, 2), 'velocity: ').draw(win) self.vel = Entry(Point(3, 2), 5).draw(win) self.vel.setText(str(vel)) Text(Point(1, 3), 'Height').draw(win) self.height = Entry(Point(3, 3), 5).draw(win) self.height.setText(str(height)) self.fire = Button(win, Point(1, 4), 1.25, 0.5, 'Fire!') self.fire.activate() self.quit = Button(win, Point(3, 4), 1.25, 0.5, 'Quit') self.quit.activate() def interact(self): while True: pt = self.win.getMouse() if self.quit.clicked(pt): print('quit') return "Quit" if self.fire.clicked(pt): print('fire') return "Fire" def getValues(self): a = float(self.angle.getText()) v = float(self.vel.getText()) h = float(self.height.getText()) return a, v, h def close(self): self.win.close()
def drawPlayerNameEntry(game_panel): # Creates text prompting user for player name player_name_text = Text(Point(80, 70), "Player Name:") player_name_text.setStyle("bold") player_name_text.setSize(14) player_name_text.draw(game_panel) # Provides an entry box for user to enter player name player_name_entry = Entry(Point(195, 70), 18) player_name_entry.setFill("white") player_name_entry.draw(game_panel) # Return objects return player_name_text, player_name_entry
def ten_coloured_rectangles(): """ 8. Write a function, ten_coloured_rectangles(), that allows the user to draw 10 coloured rectangles on the screen. The user should choose the coordinates of the top-left and bottom-right corners by clicking on the window. The colour of each rectangle should be chosen by the user by entering a colour in a text entry box at the top of the window. The colour of each rectangle is given by the string that is in this box when the user clicks its bottom- right point. The entry box should initially contain the string 'blue'. Assume that the user never enters an invalid colour into the entry box. """ win = GraphWin("Ten Rectangles", 400, 700) message = Text(Point(200, 15), "Enter a colour for the rectangle").draw(win) input_box = Entry(Point(200, 50), 10).draw(win) input_box.setText("blue") hint = Text(Point(200, 80), "Click the top left point").draw(win) for _ in range(10): hint.setText("Click the top left point") p1 = win.getMouse() hint.setText("Click the bottom left point") p2 = win.getMouse() rectangle = Rectangle(p1, p2).draw(win) try: rectangle.setFill(input_box.getText()) except TclError: rectangle.setFill("") input_box.setText("") hint.setText("") message.setText("You have used up all of your rectangles") await_user_input(win)
def __init__(self, angle, vel, height): self.win = win = GraphWin('Init', 200, 300) win.setCoords(0, 4.5, 4, 0.5) Text(Point(1, 1), 'angle: ').draw(win) self.angle = Entry(Point(3, 1), 5).draw(win) self.angle.setText(str(angle)) Text(Point(1, 2), 'velocity: ').draw(win) self.vel = Entry(Point(3, 2), 5).draw(win) self.vel.setText(str(vel)) Text(Point(1, 3), 'Height').draw(win) self.height = Entry(Point(3, 3), 5).draw(win) self.height.setText(str(height)) self.fire = Button(win, Point(1, 4), 1.25, 0.5, 'Fire!') self.fire.activate() self.quit = Button(win, Point(3, 4), 1.25, 0.5, 'Quit') self.quit.activate()
def __init__(self, angle, vel, height): """ Build and display the ingut window """ self.win = win = GraphWin("Initial Values", 200, 300) win.setCoords(0, 4.5, 4, 0.5) Text(Point(1, 1), "Angle").draw(win) self.angle = Entry(Point(3, 1), 5).draw(win) self.angle.setText(str(angle)) Text(Point(1, 2), "Velocity").draw(win) self.vel = Entry(Point(3, 2), 5).draw(win) self.vel.setText(str(vel)) Text(Point(1, 3), "Height").draw(win) self.height = Entry(Point(3, 3), 5).draw(win) self.height.setText(str(height)) self.fire = Button(win, Point(1, 4), 1.25, 0.5, "Fire!") self.fire.activate() self.quit = Button(win, Point(3, 4), 1.25, 0.5, "Quit") self.quit.activate()
class Input: def __init__(self, label, default, point, width, least, most): # Because it's monospace font face = 'courier' self.default = default self.min = least self.max = most self.entry = Entry(point, width) self.entry.setFace(face) self.entry.setText(default) # This only works because the font face is courier (monospace) # It more than double the label length, so that when it's center # matches that of the input, the text aligns perfectly on the left. self.label = Text(point, label + ': ' + (' ' * (6 + len(label)))) self.label.setFace('courier') def draw(self, win): self.entry.draw(win) self.label.draw(win) return self def validate(self): entry = self.entry value = entry.getText() try: float(value) # Check to see if it's even a number except ValueError: value = self.default entry.setText(value) if float(value) < self.min or float(value) > self.max: entry.setText(self.default) return self def getValue(self): return self.validate().entry.getText()
def main(): win = graphics.GraphWin('Investment Grow Chart',320,240) win.setBackground('White') win.setCoords(-1.75,-9000,11.5,15400) Text(Point(4.87,13500),'Future Value Calculator').draw(win) Text(Point(4.5,-2000),'Input first principal:').draw(win) inputP = Entry(Point(9,-2000),6) inputP.setText('0') inputP.draw(win) Text(Point(3,-4000),' Input interest rate in decimal:').draw(win) inputR = Entry(Point(9,-4000),6) inputR.setText('0.0') inputR.draw(win) button = Rectangle(Point(2,-6000),Point(8,-8500)) button.setFill('Green') button.draw(win) buttontext = Text(Point(5,-7250),'Show Result!:') buttontext.draw(win) win.getMouse() p = eval(inputP.getText()) r = eval(inputR.getText()) Text(Point(-1,0),'0 K').draw(win) Text(Point(-1,2500),'2.5K').draw(win) Text(Point(-1,5000),'5 K').draw(win) Text(Point(-1,7500),'7.5K').draw(win) Text(Point(-1,10000),'10 K').draw(win) bar = Rectangle(Point(0,0),Point(1,p)) bar.setFill('green') bar.setWidth(2) bar.draw(win) for i in range(1,11): p = p*(1+r) bar= Rectangle(Point(i,0),Point(i+1,p)) bar.setFill('Green') bar.setWidth(2) bar.draw(win) buttontext.setText('Quit.') win.getMouse() win.close()
def main(): win = graphics.GraphWin('Investment Grow Chart', 320, 240) win.setBackground('White') win.setCoords(-1.75, -9000, 11.5, 15400) Text(Point(4.87, 13500), 'Future Value Calculator').draw(win) Text(Point(4.5, -2000), 'Input first principal:').draw(win) inputP = Entry(Point(9, -2000), 6) inputP.setText('0') inputP.draw(win) Text(Point(3, -4000), ' Input interest rate in decimal:').draw(win) inputR = Entry(Point(9, -4000), 6) inputR.setText('0.0') inputR.draw(win) button = Rectangle(Point(2, -6000), Point(8, -8500)) button.setFill('Green') button.draw(win) buttontext = Text(Point(5, -7250), 'Show Result!:') buttontext.draw(win) win.getMouse() p = eval(inputP.getText()) r = eval(inputR.getText()) Text(Point(-1, 0), '0 K').draw(win) Text(Point(-1, 2500), '2.5K').draw(win) Text(Point(-1, 5000), '5 K').draw(win) Text(Point(-1, 7500), '7.5K').draw(win) Text(Point(-1, 10000), '10 K').draw(win) bar = Rectangle(Point(0, 0), Point(1, p)) bar.setFill('green') bar.setWidth(2) bar.draw(win) for i in range(1, 11): p = p * (1 + r) bar = Rectangle(Point(i, 0), Point(i + 1, p)) bar.setFill('Green') bar.setWidth(2) bar.draw(win) buttontext.setText('Quit.') win.getMouse() win.close()
def show_total(amount): totalWin = GraphWin("Transaction", 250,250) totalWin.setBackground("Yellow") amountText = Text(Point(125,50), amount) amountText.setStyle("bold") amountText.draw(totalWin) amountLabel = Text(Point(50,50), "Total:") amountLabel.draw(totalWin) tenderedBox = Entry(Point(125,100), 5) tenderedBox.setText("0") tenderedBox.setFill("white") tenderedBox.draw(totalWin) label = Text(Point(50,100), "Given: ") label.draw(totalWin) button = Image(Point(125, 200), "icons/button.png") button.draw(totalWin) buttonRect = Rectangle(Point(50,184), Point(203,218)) calcFlag = False while True: errorFlag = False try: click = totalWin.getMouse() except: totalWin.close() break if(isPtInRect(buttonRect, click)): if(calcFlag): change.undraw() try: tendered = tenderedBox.getText() except: errorFlag = True tenderedBox.setText("0") if(float(tendered) < amount): errorFlag = True tenderedBox.setText(str(amount)) if(not errorFlag): change = Text(Point(125, 150), "Change: " + str(float(tendered) - amount)) change.setStyle("bold") change.draw(totalWin) calcFlag = True return
def graphics(): dict = { 'jsmith': '1994', 'rstein': '2010', 'rong': '1945', 'annah': '2020' } holder = { 'jsmith': 'John Smith', 'rstein': 'Rebecca Stein', 'rong': 'Ronald Gray', 'annah': 'Anna Heller' } from graphics import GraphWin, Rectangle, Entry, Text, Point, Circle win = GraphWin('Automated Transaction Machine', 500, 500) win.setCoords(0, 0, 40, 40) Welcome_message = Text(Point(20, 35), 'Welcome to the Automated Transaction Machine') Rect = Rectangle(Point(2, 2), Point(37, 37)) Rect.draw(win) Welcome_message.draw(win) Pin_value = Text(Point(10, 32), '\tPlease input your 1.UserID and 2. PIN below') Pin_value.setSize(10) Pin_value.draw(win) userID = Entry(Point(8, 30), 8) userID.draw(win) pin = Entry(Point(8, 26), 8) pin.draw(win) win.getMouse() x = pin.getText() y = userID.getText() Pin_value.undraw() userID.undraw() pin.undraw() while True: try: holder = CheckingAccount(y, x) break except ValueError: Incorrect_value = Text(Point(10, 32), '\tYour PIN is incorrect. Try Again') Incorrect_value.draw(win) pin = Entry(Point(8, 26), 8) pin.draw(win) win.getMouse() x = pin.getText() Incorrect_value.undraw() pin.undraw() except NameError: Incorrect_value = Text(Point(10, 32), '\tYour UserID is incorrect. Try Again') Incorrect_value.draw(win) userID = Entry(Point(8, 30), 8) userID.draw(win) win.getMouse() y = userID.getText() Incorrect_value.undraw() userID.undraw() userID.undraw() pin.undraw() Welcome = Text( Point(20, 25), "Welcome " + str(holder) + "! It is a pleasure serving you today!") Welcome.draw(win) win.getMouse() Welcome.undraw() Option = Text(Point(20, 25), 'Would you like to withdraw or deposit') Option.draw(win) win.getMouse()
# pip install pyautogui import pyautogui from graphics import GraphWin, Circle, Point, Entry, color_rgb import time win = GraphWin("pipetka", 200, 200, autoflush=True) # создаем графическую форму размером 200х200 и элементы на ней x, y = pyautogui.position() # получаем в x, y координаты мыши r, g, b = pyautogui.pixel(x, y) # получаем в r, g, b цвет ColorDot = Circle(Point(100, 100), 25) # создаем точку, отображающую цвет ColorDot.setFill(color_rgb(r, g, b)) # устанавливает ей заливку из ранее полученных цветов ColorDot.draw(win) # рисуем на форме win RGBtext = Entry(Point(win.getWidth() / 2, 25), 10) # создаем RGB вывод RGBtext.draw(win) # рисуем на форме win RGBstring = Entry(Point(win.getWidth() / 2, 45), 10) # создаем вывод цвета в web стиле RGBstring.draw(win) # рисуем на форме win Coordstring = Entry(Point(win.getWidth() / 2, 185), 10) # создаем отображение координат Coordstring.draw(win) # рисуем на форме win while True: # цикл перереисовки формы time.sleep(0.1) # задержка в 0.1 с, чтобы питон не сходил с ума x, y = pyautogui.position() # получаем в x, y координаты мыши r, g, b = pyautogui.pixel(x, y) # получаем в r, g, b цвет ColorDot.setFill(color_rgb(r, g, b)) # Обновляем цвет RGBtext.setText(pyautogui.pixel(x, y)) # Обновляем RGB