def guiThread(self): root = Tk() pane = Frame(root) pane.pack(fill = BOTH, expand = True) exit_button = Button(pane, text='Exit Program', command=root.destroy) exit_button.pack(side = LEFT, expand = True, fill = BOTH) msg = Message(root, text="TEST TEST TEST") msg.config(font=('Consolas', 10, '')) msg.pack() def updateImage(): #print("in updateImage()") if not self.queueGUI.empty(): while not self.queueGUI.empty(): imgText = self.queueGUI.get() #print("set Text to {}".format(imgText)) msg.configure(text=imgText) #if len(self.queueGUI.queue): #print("clear queue") #self.queueGUI.queue.clear() #else: #print("queue empty") root.after(100, updateImage) root.after(100, updateImage) root.mainloop()
def displayHighScores(self): top = tk.Toplevel() top.title("High Scores") try: f = open("HS" + self.level, "r") except IOError: f= open("HS" + self.level,"w+") scores = [] f = open("HS" + self.level, "r") line = f.readline() counter = 1 message = "" # variable containing the string to show in the message while line and counter < 11: if 'SEP' in line: #we re separating the player name and his score with the SEP message += str(counter) + " - " + line.split("SEP")[0].strip() + " : " + line.split("SEP")[1].strip() + "\n" counter = counter + 1 line = f.readline() msg = Message(top, text=message, width=200) msg.config(font=("Courier", 12)) msg.pack() button = tk.Button(top, text="Ok", command=top.destroy) button.pack() pass
def train(mode: int, dt, nb_repetitions=2, subtitle=""): """ Display chords every dt seconds. Once all the chords have been played once, another round can begin.""" my_list = name_to_content(mode_to_name(mode)) elements_already_chosen = [] n = len(my_list) for i in range(nb_repetitions * n): if len(elements_already_chosen) == n: elements_already_chosen = [] el = choice(my_list) # Check that the element has not been played already in the current cycle. while el in elements_already_chosen: el = choice(my_list) # Update list of already played elements elements_already_chosen.append(el) # Display root = Tk() root.attributes('-fullscreen', True) root.after(floor(dt * 1000), lambda: root.destroy()) msg = Message(root, text=el) msg.config(font=('times', 100, 'italic bold underline')) msg.pack() # Optional message msg1 = Message(root, text=subtitle) msg1.config(font=('times', 50)) msg1.pack() root.mainloop()
def timed_messagebox(title, message): messagebox = Toplevel() messagebox.title(title) m = Message(messagebox, text=message, padx=100, pady=100) m.config(font=('TkDefaultFont', 20)) m.pack() messagebox.after(3000, messagebox.destroy)
def create(): top = Toplevel() top.title('使用提示') top.geometry("400x400") t = "关于照片,新建一个存放图片的文件,用英文命名,然后存里面的图片也用英文命名。关于音乐: 新建一个名字叫音乐的文件,把歌曲添加到该文件夹。" msg = Message(top, text=t) msg.config(font=('times', 24, 'italic')) msg.place(x=0, y=0)
def instruction(self): window = Tk() window.title("Instructions") for i in self.instructions: Label(window, text="Question #" + str(self.instructions.index(i) + 1), font="times 16 bold").pack() msg = Message(window, text=i, width=700) msg.config(font=('times', 14)) msg.pack() window.mainloop()
def big_yes_no(title, message): messagebox = Toplevel() messagebox.title(title) m = Message(messagebox, text=message, padx=100, pady=100) m.config(font=('TkDefaultFont', 20)) m.grid(row=0, column=1) yes = Button(messagebox, text='Yes', command=lambda x=messagebox: destroy(1, x)) yes.config(font=('TkDefaultFont', 20)) yes.grid(row=1, column=0) no = Button(messagebox, text='No', command=lambda x=messagebox: destroy(0, x)) no.config(font=('TkDefaultFont', 20)) no.grid(row=1, column=2)
def Message(root, style = "", **options): props = { 'bg': load_color(style)['bgColor'], 'fg': load_color(style)['color'], } props.update(**options) M = TKMessage( root ) print(props) M.config(props) M.pack(pady=10)
def shard_popup(self, e): if (self.algtype != 'BIP39xor'): return shard_text = None lb = e.widget['text'] part = '' if lb == 'Shard 1': shard_text = self.shard_tb[0].get('1.0', END + '-1c') part = 'SHARD 1' elif lb == 'Shard 2': shard_text = self.shard_tb[1].get('1.0', END + '-1c') part = 'SHARD 2' elif lb == 'Shard 3': shard_text = self.shard_tb[2].get('1.0', END + '-1c') part = 'SHARD 3' elif lb == 'Seed Phrase': shard_text = self.seed_tb.get('1.0', END + '-1c') part = 'SEED' else: return sp = seedpart.BIP39xor() words = shard_text.split() try: shard = bip39shard(words) except Exception as e: messagebox.showerror('SeedPart Shard Info', str(e)) return s = ' %s\n' % part s += '---------------------------\n' s += 'Number Word Index\n' s += '---------------------------\n' for i in range(0, len(shard.words)): s += '{:>6} {:12} {:>5}\n'.format(i + 1, shard.words[i].word, shard.words[i].num) popup = Message(Toplevel(master=self.root), text=s) popup.config(font=('Courier', 12)) popup.pack()
def vis_thread(): global txt, color, txt2, color2 def update(): global txt, color, txt2, color2 msg.config(text=txt, background=color) msg2.config(text=txt2, background=color2) root.after(250, update) root = Tk() root.geometry("900x600") msg = Message(root, text=txt, background=color) msg.config(font=('times', 200, 'italic bold')) msg.pack() msg2 = Message(root, text=txt2, background=color2) msg2.config(font=('times', 70, 'italic bold')) msg2.pack() root.after(250, update) root.mainloop()
███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ████████████ ◦ ███ ◦ █████████ ◦ ███ ◦ ███████████████ ◦ ███ ◦ ███ ◦ ███ ◦ ██████████████████ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███████████████ ◦ ██████ ██████ ◦ ███████████████ ◦ ███ ◦ ███ ◦ ███ ◦ ███████████████ ◦ █████████ ◦ ██████ ███ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ███ ◦ ███████████████████████████ ◦ ███ ◦ ███ ◦ ████████████ ████████████ ◦ ███ ◦ ███████████████ ◦ █████████ ◦ ██████ ███ ◦ ███ ███ ◦ ◦ ◦ ◦ ◦ ███ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ███ ◦ ███ ██████ ◦ █████████ ◦ █████████ ◦ ███ ◦ █████████ ◦ ███ ◦ █████████ ◦ ███ ◦ █████████ ◦ ███████████████ ◦ ███ ███ ◦ ███ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ███ ◦ ███ ███ ◦ █████████ ◦ █████████ ◦ █████████ ◦ ███████████████████████████ ◦ ███ ◦ ███████████████ ◦ ████████████ ███ ◦ ███ ███ ◦ ◦ ◦ ███ ◦ ███ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ███ ◦ ███ ◦ ██████ ◦ ███ ◦ ███ ██████ ◦ █████████ ◦ ███ ◦ █████████ ◦ ███ ◦ █████████ ◦ ███ ◦ ███████████████ ◦ ███ ███ ◦ ◦ ◦ ◦ ███ ◦ ███ ◦ ███ ███ ◦ ◦ ◦ ███ ◦ ███ ◦ ███ ◦ ███ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ██████ ◦ █████████ ◦ ███ ◦ █████████ ◦ █████████ ◦ █████████ ◦ ███ ◦ ███ ◦ █████████ ◦ ███████████████ ◦ ███ ◦ ███ ◦ ███ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ███ ███ ◦ ███ ◦ ███████████████████████████████████████████████████ ◦ █████████████████████ ◦ █████████████████████ ◦ ███ ███ ◦ ███ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ███ ███ ◦ ███████████████████████████████████████ ◦ ███ ◦ ███ ◦ ███ ◦ █████████ ◦ ███ ◦ ███ ◦ ███ ◦ █████████ ◦ ███ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ◦ ◦ ◦ ◦ ◦ ███ ◦ ◦ ◦ ███ ███ █████████ █████████ █████████ ███████████████ █████████ None""" msg = Message(root, text=AAA) # Font is a tuple of (font_family, size_in_points, style_modifier_string) msg.config(font=('Consolas', 10, '')) msg.pack() root.mainloop()
""" Tkinter example: Window size, title, label and message. """ from tkinter import Tk, Label, Message __author__ = "paulogp" __copyright__ = "Copyright (C) 2015 Paulo G.P." __date__ = "16/12/2015" if __name__ == "__main__": root = Tk() # title root.title("Tkinter Title") # size root.geometry("300x150+50+50") # label label1 = Label(root, text="One Label") label1.pack(padx=0, ipady=20) # text msg = Message(root, text="Hello, world!") msg.config(font=("times", 12, "italic bold underline")) msg.pack() # do root.mainloop()
"""Message Widow. Stand-alone example from Tk Assistant. stevepython.wordpress.com""" from tkinter import Message, Tk root = Tk() root.title('Message window example') msg_text = 'Whoever invented auto-correct ' \ 'should burn in hello.' msg = Message(root, text=msg_text) msg.config(bg='springgreen', font=('verdant', 24, 'italic')) msg.grid() root.mainloop()
class BattleshipsDemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) # empty string for platform's default settings locale.setlocale(locale.LC_ALL, '') self.master = tk tk.title(APP_TITLE) tk.resizable(False, False) try: if WINDOWS: tk.iconbitmap("200x200/icon.ico") else: tk.iconbitmap("@200x200/icon.xbm") except Exception as e: print(e) atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_entry = Entry(self.middleFrameLeft) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=0, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(APP_TITLE + " (Not Logged In)") self.cancel_game() self.bot_id = 'housebot-competition' self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = '******' res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + APP_TITLE) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_entry.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) self.balance['text'] += ' sat' def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': BATTLESHIPS_GAME_TYPE_ID } url = BASE_URL + GET_LIST_OF_GAME_STYLES_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): self.game_styles_listbox.insert( index, GAME_STYLE_LISTBOX_TEXT.format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() self.find_game() if self.game_cancelled: break self.play_game() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" opponent_id = self.specify_opponent_entry.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = BASE_URL + OFFER_GAME_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) game_style_details = self.game_styles_listbox.get('active').split( " | ") title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += format(' / Land: ' + game_style_details[6].split(" ")[2] + '%') title += format(' / Deals: ' + game_style_details[5].split(" ")[1]) title += format(' / ' + game_style_details[7]) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = battleships_move.calculateMove(game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = BASE_URL + MAKE_MOVE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = BASE_URL + POLL_FOR_GAME_STATE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) def cancel_game(self): if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = BASE_URL + CANCEL_GAME_OFFER_EXTENSION BattleshipsDemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- resultText Message object no longer exists") @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
import numpy as np import pandas as pd import tkinter as tk from tkinter import Listbox, Message, Button, Canvas from PIL import Image, ImageTk m = tk.Tk() m.configure(background="blue") m.title("This is Mao") ourMessage = 'Mao, there are no rules' messageVar = Message(m, text=ourMessage) messageVar.config(bg='orange') messageVar.pack() y = np.array([ "1)Rule1", "2)Rule2", "3)Rule3", "4)Rule4", "5)Rule5", "6)Rule6", "7)Rule7" ]) lb = Listbox(m) def easy(): x = np.random.randint(0, 3) lb.insert(x, y[x]) lb.pack() def medium(): x = np.random.randint(0, 5) lb.insert(x, y[x]) lb.pack()
pred = Ensemble_predict(P_test, params) print(pred) # Get the most common class of the n test samples PREDICTION_CLASS = Counter(pred).most_common(1)[0][0] #################### ### Finish Model ### #################### ############################################################# #### 4) Display message with greeting for prediction name ### ############################################################# ''' This portion of the code will create a Pop up window with the name corresponding to the predicted class by the model. It takes the names and classes from the name_dict created on the first line of code Inputs: + PREDICTED_CLASS (int): Predicted class number from model ''' mw = Tk() msg = Message(mw, text="Hello {}!".format(name_dict[PREDICTION_CLASS])) msg.config(font=("Courier", 44)) msg.config(width=800) msg.config(fg='red') msg.pack() mainloop() ############################################################## #### End Display message with greeting for prediction name ### ##############################################################
""" Message widget example """ from tkinter import mainloop, Message, X, YES msg = Message(text="Oh by the way, which one's Pink?") msg.config(bg='pink', font=('times', 16, 'italic')) msg.pack(fill=X, expand=YES) mainloop()
enter = Entry(root) enter.pack(side=LEFT) def Button_Click(Event): window.pack() window.update() frame.pack() Selection(main_list) button = Button(root, text="Search & Sort") button.pack(side=LEFT) button.bind("<ButtonPress-1>",Button_Click) mess = Message(root, text="Ok, the pink bar is the value searched for" ) mess.config(bg='lightgreen', font=('times', 14, 'italic'),width = 500 ) mess.pack(side = BOTTOM) def change_color(bar,color): """ Suggested for changing the color in real time, but does not work the way I want it to. """ window.itemconfig(bar, fill=color) def Swap(main_list,x,y): """ Swaps x and y to test if one is smaller and fixes the list. """ tmp = main_list[x] main_list[x] = main_list[y]
# change_font.py from tkinter import Tk, Message root = Tk() msg = Message(root, text='Hello, world!') # Font is a tuple of (font_family, size_in_points, style_modifier_string) msg.config(font=('times', 48, 'italic bold underline')) msg.pack() root.mainloop()
def guiThread(self): root = Tk() pane = Frame(root) pane.pack(fill=BOTH, expand=True) exit_button = Button(pane, text='Exit Program', command=root.destroy) exit_button.pack(side=LEFT, expand=True, fill=BOTH) msg = Message(root, text="TEST TEST TEST") msg.config(font=('Consolas', 10, '')) msg.pack() def updateImage(): #print("in updateImage()") if not self.queueGUI.empty(): while not self.queueGUI.empty(): imgText = self.queueGUI.get() #print("set Text to {}".format(imgText)) msg.configure(text=imgText) #if len(self.queueGUI.queue): #print("clear queue") #self.queueGUI.queue.clear() #else: #print("queue empty") root.after(100, updateImage) def updateImage2(): #print("in updateImage()") if not self.computer.output.empty(): oldLine = '' imgText = '' while True: try: el = self.computer.output.get() current = chr(el) except: print("bla bla bla {}".format(el)) continue if current in ['<', '>', 'v', '^']: bla = '█' + current + '█' elif current in ['x', 'X']: bla = ' ' + current + ' ' elif current == '#': bla = '███' elif current == '\n': bla = current else: bla = ' ' imgText += bla if current == "\n" and oldLine == "\n": break oldLine = current #print("set Text to {}".format(imgText)) msg.configure(text=imgText) #if len(self.queueGUI.queue): #print("clear queue") #self.queueGUI.queue.clear() #else: #print("queue empty") root.after(100, updateImage2) root.after(100, updateImage2) root.mainloop()
class DemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings self.master = tk self.config = json.load(open('config.json', 'r')) self.config['COMBOBOX_INDEX'] = sorted(self.config['COMBOBOX_INDEX'], key=lambda x: x[0]) self.game_type = int( args.gametype ) if args.gametype else self.config["DEFAULT_GAME_TYPE_ID"] tk.title(self.config["APP_TITLE"]) tk.resizable(False, False) self.get_icon() atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameTypeCmb = ttk.Combobox( self.middleFrameLeft, state="disabled", values=tuple((game[0]) for game in self.config['COMBOBOX_INDEX'])) if self.game_type != self.config['NULL_GAME_TYPE_ID']: index = [ i for i in range(len(self.config['COMBOBOX_INDEX'])) if self.config['COMBOBOX_INDEX'][i][1] == self.game_type ][0] self.gameTypeCmb.current( index) # Default selection matches default game type id self.gameTypeCmb.bind("<<ComboboxSelected>>", self.game_type_selected) self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_cmb = ttk.Combobox( self.middleFrameLeft, values=self.config['AVAILABLE_OPPONENTS']) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = None # Initialise as none before updating in create_visuals() self.opponent = None # Initialise as none before updating in create_visuals() self.create_visuals() self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameTypeCmb.grid(row=0, column=0, columnspan=1, sticky=W + E) self.gameStyleLabel.grid(row=1, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=1, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_cmb.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None and args.password is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True if args.gamestyle is not None: i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(self.config["APP_TITLE"] + " (Not Logged In)") self.cancel_game() self.bot_id = None self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.gameTypeCmb.config(state="disabled") self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = self.bot_password_entry.get() res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + self.config["APP_TITLE"]) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.gameTypeCmb.config(state="readonly") self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.clear_board() self.opponent.clear_board() self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_cmb.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': self.game_type } url = self.config["BASE_URL"] + self.config[ "GET_LIST_OF_GAME_STYLES_EXTENSION"] return DemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): if self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BATTLESHIPS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) elif self.game_type == self.config[ "NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["NOUGHTS_AND_CROSSES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["TRAVELLING_SALESDRONE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['TotalCities'], game_style['GameTypeSpecificInfo']['DealLength'])) elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["PREDICTIVE_TEXT_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['Number of Sentences'], game_style['GameTypeSpecificInfo'] ['Switched Words Game'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["TWIST_CUBE_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['cubeSize'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["SLIDING_PUZZLE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['RowSize'], game_style['GameTypeSpecificInfo']['ColumnSize'], game_style['GameTypeSpecificInfo']['TimeLimit'])) elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BLURRY_WORD_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumImages'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["MASTERMIND_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumPegs'], game_style['GameTypeSpecificInfo']['NumColours'], game_style['GameTypeSpecificInfo'] ['DuplicatesAllowed'])) elif self.game_type == self.config[ "WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WAREHOUSE_LOGISTICS_GAME_STYLE_LISTBOX_TEXT"]. format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][0], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][1])) elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["FOUR_IN_A_ROW_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Connections'])) elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WHO_IS_WHO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumCharacters'], game_style['GameTypeSpecificInfo']['ComparisonRound'])) elif self.game_type == self.config[ "REVERSING_STONES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["REVERSING_STONES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Holes'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["CHECKERS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["GO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], "CAPTURE" if game_style['GameTypeSpecificInfo']['IsCaptureGo'] else game_style['GameTypeSpecificInfo']['ScoringMethod'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["LEXICO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['TileMultipliers'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["DOMINOES_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['SpotNo'], game_style['GameTypeSpecificInfo']['Timeout ms'])) else: raise ValueError('INVALID GAME TYPE PARAMETER') self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.game_styles_listbox.unbind('<Double-1>') self.game_styles_listbox.unbind('<Return>') self.game_styles_listbox.config(state=DISABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_type_selected(self, _): self.game_type = self.config["COMBOBOX_INDEX"][ self.gameTypeCmb.current()][1] res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) self.get_icon() self.player.destroy() self.opponent.destroy() self.create_visuals() def get_icon(self): try: if WINDOWS: self.master.iconbitmap("assets/{0}/icon.ico".format( self.game_type)) else: self.master.iconbitmap("./assets/{0}/icon.xbm".format( self.game_type)) except Exception as e: print(e) def create_visuals(self): if self.game_type == self.config["NULL_GAME_TYPE_ID"]: self.player = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table self.opponent = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.player = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table self.opponent = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.player = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table self.opponent = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.player = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table self.opponent = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.player = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table self.opponent = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.player = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table self.opponent = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.player = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table self.opponent = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.player = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table self.opponent = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.player = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table self.opponent = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.player = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table self.opponent = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.player = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table self.opponent = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["REVERSING_STONES_GAME_TYPE_ID"]: self.player = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table self.opponent = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.player = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table self.opponent = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.player = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table self.opponent = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.player = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table self.opponent = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.player = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table self.opponent = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table else: raise ValueError('INVALID GAME TYPE PARAMETER') self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() mover.persistentData = {} self.find_game() self.update_balance() if self.game_cancelled: break self.play_game() self.update_balance() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" self.cancel_game( ) # Cancel the last outstanding game offer that was made opponent_id = self.specify_opponent_cmb.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = self.config["BASE_URL"] + self.config["OFFER_GAME_EXTENSION"] return DemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = mover.calculate_move(self.game_type, game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print(str(move_results)) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = self.config["BASE_URL"] + self.config["MAKE_MOVE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "POLL_FOR_GAME_STATE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) def cancel_game(self): print("Cancelling last game offer") if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "CANCEL_GAME_OFFER_EXTENSION"] DemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- Demo client has been closed") def update_balance(self): res = self.get_list_of_game_styles() self.set_balance(res['Balance']) @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
from tkinter import Tk, Message root = Tk() msg = Message(root, text='Welcome to tkinter programming!!!') msg.config(font=('monaco', 15, 'bold underline')) msg.pack() root.mainloop()
class GUI: """ A class to represent the gui for this program. """ def __init__(self): # There may be other compatible types I am not aware of self.image_types = ['png', 'jpg', 'gif', 'jpeg'] # Create window self.window = Tk() self.window.title("Image Saturation Reader") self.window.state("zoomed") # Set default variables self.current_image_name = "None Selected" self.current_image = None self.current_mode = 'area' self.canvas_size = None self.corners = [] self.sight_lines = [] # Find screen height self.width = self.window.winfo_screenwidth() self.height = self.window.winfo_screenheight() # Populate window self._generate_window() # Bind events self.canvas.bind('<Motion>', self.motion) self.canvas.bind('<Leave>', self.leave) self.canvas.bind('<Button-1>', self.click) # Final stylizations self.area_mode_button.config(relief=SUNKEN) def _generate_window(self): """ Generate the components inside the window. """ # Left-side information panel info_panel = ttk.Frame(self.window) # Create components inside left panel choose_image = Button(info_panel, text='Choose Image', command=self.choose_image) image_label = Message(info_panel, text='Image:', width=40) self.image_name = Message(info_panel, text=self.current_image_name, width=100) self.image_width = Message(info_panel, text='W: ', width=50) self.image_height = Message(info_panel, text='H: ', width=50) self.separator = Message(info_panel, text='=======', width=75) self.x = Message(info_panel, text='x: ', width=40) self.y = Message(info_panel, text='y: ', width=40) self.r = Message(info_panel, text='r: ', width=40) self.g = Message(info_panel, text='g: ', width=40) self.b = Message(info_panel, text='b: ', width=40) self.num_pixels = Message(info_panel, text='# Pixels: ', width=50) self.hue = Message(info_panel, text='Hue: ', width=75) self.saturation = Message(info_panel, text='Saturation: ', width=75) self.value = Message(info_panel, text='Value: ', width=75) self.pixel_mode_button = Button(info_panel, text='Pixel Mode', command=self.pixel_mode) self.area_mode_button = Button(info_panel, text='Area Mode', command=self.area_mode) # Place the components inside left panel choose_image.grid(padx=5, pady=5, sticky="N") image_label.grid(sticky=W) self.image_name.grid(sticky=W) self.image_width.grid(sticky=W) self.image_height.grid(sticky=W) self.separator.grid() self.x.grid(sticky=W) self.y.grid(sticky=W) self.r.grid(sticky=W) self.g.grid(sticky=W) self.b.grid(sticky=W) self.num_pixels.grid(sticky=W) self.hue.grid(sticky=W) self.saturation.grid(sticky=W) self.value.grid(sticky=W) self.area_mode_button.grid() self.pixel_mode_button.grid() # Create right panel components self.canvas = Canvas(self.window, width=self.width, height=self.height, bg='lightblue') # Add two sides to final window info_panel.grid(column=1, row=1) self.canvas.grid(column=2, row=1, sticky="nesw") def choose_image(self): self.current_image_name = askopenfilename() if self.current_image_name.split('.')[-1] in self.image_types: self.image_name.configure( text=self.current_image_name.split('/')[-1]) self.open_image() self.clear_drawing_data() def open_image(self): if self.canvas_size is None: self.set_canvas_size() self.current_image = Image.open(self.current_image_name) self.current_image.thumbnail(self.canvas_size, Image.ANTIALIAS) current_image_tk = ImageTk.PhotoImage(self.current_image) width = current_image_tk.width() height = current_image_tk.height() self.image_width.config(text='W: ' + str(width)) self.image_height.config(text='H: ' + str(height)) self.canvas.config(width=width - 4, height=height - 4) self.canvas.create_image(round(width / 2), round(height / 2), anchor=CENTER, image=current_image_tk) self.canvas.image = current_image_tk def set_canvas_size(self): self.canvas_size = (self.canvas.winfo_width(), self.window.winfo_height()) def click(self, event): """ Clicking within the canvas. """ if self.current_image is not None: x, y = event.x, event.y if self.current_mode == 'area': if not self.corners: self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) elif len(self.corners) == 1: self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) x1, y1, *_ = self.canvas.coords(self.corners[0]) x2, y2, *_ = self.canvas.coords(self.corners[1]) self.get_pixel_data(x1, y1, x2, y2) else: self.clear_drawing_data() self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) elif self.current_mode == 'pixel': self.get_pixel_data(x, y, x, y) def get_pixel_data(self, x1, y1, x2, y2): x1 = round(x1) y1 = round(y1) x2 = round(x2) y2 = round(y2) if x2 < x1: x1, x2 = x2, x1 if y2 < y1: y1, y2 = y2, y1 total_hue = 0 total_saturation = 0 total_value = 0 total_r = 0 total_g = 0 total_b = 0 c = 0 for y in range(y1, y2 + 1): for x in range(x1, x2 + 1): r, g, b, *_ = self.current_image.getpixel((x, y)) data = rgb_to_hsv(r, g, b) total_hue += data[0] total_saturation += data[1] total_value += data[2] total_r += r total_g += g total_b += b c += 1 avg_hue = round((total_hue / c), 2) avg_saturation = round((total_saturation / c) * 100, 2) avg_value = round((total_value / c), 2) avg_r = round((total_r / c), 2) avg_g = round((total_g / c), 2) avg_b = round((total_b / c), 2) self.write_pixel_data(avg_hue, avg_saturation, avg_value, avg_r, avg_g, avg_b, c) def write_pixel_data(self, hue, sat, val, r, g, b, c): self.num_pixels.configure(text='# Pixels: ' + str(c)) self.hue.configure(text='Hue: ' + str(hue)) self.saturation.configure(text='Saturation: ' + str(sat) + '%') self.value.configure(text='Value: ' + str(val)) self.r.configure(text='r: ' + str(r)) self.g.configure(text='g: ' + str(g)) self.b.configure(text='b: ' + str(b)) def leave(self, event): self.x.configure(text='x: ') self.y.configure(text='y: ') def motion(self, event): if self.current_image is not None: x, y = event.x + 1, event.y + 1 self.x.configure(text='x: ' + str(x)) self.y.configure(text='y: ' + str(y)) if len(self.corners) == 1: self.draw_sight_lines(x, y) def draw_sight_lines(self, x, y): for line in self.sight_lines: self.canvas.delete(line) lx, ly, *_ = self.canvas.coords(self.corners[0]) lx += 2 ly += 2 self.sight_lines.append( self.canvas.create_line(lx, ly, x, ly, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(lx, ly, lx, y, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(x, ly, x, y, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(lx, y, x, y, dash=(3, 3))) def pixel_mode(self): self.clear_drawing_data() self.pixel_mode_button.config(relief=SUNKEN) self.area_mode_button.config(relief=RAISED) self.current_mode = 'pixel' def area_mode(self): self.clear_drawing_data() self.area_mode_button.config(relief=SUNKEN) self.pixel_mode_button.config(relief=RAISED) self.current_mode = 'area' def clear_drawing_data(self): self.clear_drawings() self.corners = [] self.sight_lines = [] def clear_drawings(self): for line in self.sight_lines: self.canvas.delete(line) for dot in self.corners: self.canvas.delete(dot) def mainloop(self): self.window.mainloop()
class PiVision(Tk): def __init__(self, images): Tk.__init__(self) self.creer_composants() if len(images) > 0: self.initialiser_images() self.afficher_image() else: self.afficher_erreur() self.mainloop() def initialiser_images(self): liste_image = [(PhotoImage(file=image), os.path.basename(image)) for image in sorted(images)] premiere = derniere = VImage(info=liste_image.pop(0)) for image in liste_image: derniere = derniere.ajout(info=image) derniere.suivante = premiere premiere.precedente = derniere self.image_courante = premiere def creer_composants(self): self.composant_image = Label(self) self.composant_image.pack(expand=YES, fill=BOTH) self.bouton_frame = Frame(self) self.bouton_frame.pack(side=BOTTOM) self.bouton_precedent = Button(self.bouton_frame, text='Précédent', command=lambda: self.image_precedente()) self.bouton_precedent.pack(side=LEFT) self.bouton_suivant = Button(self.bouton_frame, text='Suivant', command=lambda: self.image_suivante()) self.bouton_suivant.pack(side=LEFT) self.bouton_fermer = Button(self.bouton_frame, text='Fermer', command=self.destroy) self.bouton_fermer.pack(side=LEFT) self.bind('<Left>', lambda ev: self.image_precedente()) self.bind('<Right>', lambda ev: self.image_suivante()) self.bind('<Escape>', lambda ev: self.destroy()) def image_suivante(self): self.image_courante = self.image_courante.suivante self.afficher_image() def image_precedente(self): self.image_courante = self.image_courante.precedente self.afficher_image() def afficher_image(self): image, nom_image = self.image_courante.info self.composant_image.config(image=image) self.title('%s - %s ' % (self.__class__.__name__, nom_image)) self.update() def afficher_erreur(self): self.bouton_precedent.configure(state='disable') self.bouton_suivant.configure(state='disable') self.unbind('<Left>') self.unbind('<Right>') self.erreur = Message(self.composant_image, text="Aucune image n'a été trouvée !", pady=25, padx=25, aspect=800) self.erreur.config(font=('courier', 14, 'bold')) self.erreur.pack(expand=YES, fill=BOTH) self.title('Erreur!') self.update()
def run_small_test2(): print("small Test 2") print("############") intcode = loadintCode() robot = Robot(intcode) root = Tk() pane = Frame(root) pane.pack(fill = BOTH, expand = True) def N(_event=None): robot.step(1) robot.getPossible() img = robot.getImage() msg.configure(text=img) def S(_event=None): robot.step(2) robot.getPossible() img = robot.getImage() msg.configure(text=img) def W(_event=None): robot.step(3) robot.getPossible() img = robot.getImage() msg.configure(text=img) def E(_event=None): robot.step(4) robot.getPossible() img = robot.getImage() msg.configure(text=img) def rand(_event=None): robot.exploreRand(5) img = robot.getImage() msg.configure(text=img) def find(_event=None): robot.find() img = robot.getImage() msg.configure(text=img) N_button = Button(pane, text='North', command=N) N_button.pack(side = LEFT, expand = True, fill = BOTH) S_button = Button(pane, text='South', command=S) S_button.pack(side = LEFT, expand = True, fill = BOTH) E_button = Button(pane, text='East', command=E) E_button.pack(side = LEFT, expand = True, fill = BOTH) W_button = Button(pane, text='West', command=W) W_button.pack(side = LEFT, expand = True, fill = BOTH) R_button = Button(pane, text='RAND', command=rand) R_button.pack(side = LEFT, expand = True, fill = BOTH) F_button = Button(pane, text='Find', command=find) F_button.pack(side = LEFT, expand = True, fill = BOTH) root.bind('w', N) root.bind('s', S) root.bind('a', W) root.bind('d', E) root.bind('r', rand) exit_button = Button(pane, text='Exit Program', command=root.destroy) exit_button.pack(side = LEFT, expand = True, fill = BOTH) robot.step(3) robot.step(3) robot.step(3) image = robot.getImage() msg = Message(root, text=image) msg.config(font=('Consolas', 10, '')) msg.pack() root.mainloop()