Controlling multiple menus with curses individually - python

Been trying to figure out how to switch between 2 separate menus in curses and having some difficulty.
I have 2 menus, like so:
# 1st Window.
def mainMenu(root, current_row, h, w):
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
main_win = curses.newwin(h - 1, w // 2, 1, 1)
main_win.border()
main_options = ["Enter data", "View data", "Exit"]
for idx, element in enumerate(main_options):
x = 1 + idx
y = 1
if idx == current_row:
main_win.attron(curses.color_pair(1))
main_win.addstr(y, x, element)
main_win.attroff(curses.color_pair(1))
else:
main_win.addstr(y, x, element)
main_win.refresh()
# 2nd window.
def secondMenu(root, current_row, h, w):
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
second_win = curses.newwin(h - 1, w // 2, 1, w // 2 + 1)
second_win.border()
second_options = ["Option 1", "Option 2", "Option 3"]
for idx, element in enumerate(second_options):
x = 1 + idx
y = 1
if idx == current_row:
second_win.attron(curses.color_pair(1))
second_win.addstr(y, x, element)
second_win.attroff(curses.color_pair(1))
else:
second_win.addstr(y, x, element)
second_win.refresh()
def main(root):
curses.curs_set(0)
h, w = root.getmaxyx()
current_row = 0
mainMenu(root, current_row, h, w)
while True:
key = root.getch()
if key == curses.KEY_UP and current_row > 0:
current_row -= 1
elif key == curses.KEY_DOWN and current_row < 2:
current_row += 1
elif key == ord("q"):
break
mainMenu(root, current_row, h, w)
secondMenu(root, current_row, h, w)
root.refresh()
curses.wrapper(main)
This outputs a vertically-lined menu that is highlightable on both windows. However, when I give an input both menus scroll at the same time. I'm not really sure how I can isolate control to one window or the other. Any help is really appreciated, thanks.

Question is
how I can isolate control to one window or the other.
The curses library will move the cursor to the current location in the window where the getch is called. Your example uses the root window in each case, and re-creates both menus after each getch call (creating a new window with newwin whose reference is discarded). Rather than creating (and discarding the window information), doing the newwin up front, and using the main_win or second_win variables in the loop, deciding which to use, you can switch between the menus (e.g., when you read a tab character).

Related

set and image for a canvas when user clicks and when we have multiple canvases on tkinter

I have a code that makes multiple canvases on Python tkinter (9 canvas). With this function (I destroy all item on window with destroy function at start):
def show_board(self):
self.destroy_start()
canvas_list = []
for i in range(9):
dist = {
f"canvas{i + 1}": Canvas(height=150, width=150, bg=BOARD_COLOR),
}
canvas_list.append(dist)
for n in range(len(canvas_list)):
canvas_dict = canvas_list[n]
for (key, val) in canvas_dict.items():
if n == 0 or n <= 2:
row = 0
if n == 0:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 1:
col = 1
val.grid(row=row, column=col)
elif n == 2:
col = 2
val.grid(row=row, column=col)
elif 2 < n <= 5:
row = 1
if n == 3:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 4:
col = 1
val.grid(row=row, column=col)
elif n == 5:
col = 2
val.grid(row=row, column=col)
elif n > 5:
row = 2
if n == 6:
col = 0
val.grid(row=row, column=col, padx=(125, 0))
elif n == 7:
col = 1
val.grid(row=row, column=col)
elif n == 8:
col = 2
val.grid(row=row, column=col)
# loop in canvas and get x and y of the click and set the image when user click
for item in canvas_list:
for (key, val) in item.items():
canvas_x, canvas_y = val.winfo_rootx(), val.winfo_rooty()
print(canvas_x, canvas_y)
self.check_click(can=val)
self.pl1_score_label.grid(column=0, row=3, padx=(100, 0))
self.pl2_score_label.grid(column=2, row=3)
and I want to when user clicks on window on one of these canvases for the canvas to create an image (just than canvas)
I try to do this with last loop in upper function
def display_mouse_pos(self, event):
self.window.update()
x = event.x
y = event.y
print(x, y)
def check_click(self, can):
self.window.bind("<Button-1>", self.display_mouse_pos)
can.create_image(100, 100, image=self.x_image)
self.window.update()`
but I get that image on all canvas I know problem is my function and for loop I can't find the way to check if screen get clicked or not and if its get clicked which canvas get clicked and who can I make a picture in that canvas

Tkinter - modifying buttons based on rows and columns

I want to change the colour of a button based on its row and column. I am able to search for adjacent buttons, but cant do anything with them. The code is a python version of the board game Othello, and I am trying to get the "sandwiching" aspect of the game to run. Ideally, it stays in the grid system so I am able to code to my ability
from tkinter import *
### Function to change button colour ###
def changeColour(tempButton, row, column):
if tempButton.cget("bg") == "black":
tempButton.configure (bg = "white")
else:
tempButton.configure (bg = "black")
sandwichButton(tempButton, row, column)
### Function to sandwich adjacent buttons ###
def sandwichButton(originButton, row, column):
for x in range (-1,2,1):
for y in range (-1,2,1):
aRow = (row + y)
aColumn = (column + x)
adjacentInfo = find_position(othello, aRow, aColumn)
endButtonInfo = find_position(othello, aRow + y, aColumn + x)
if adjacentInfo["row"] == (aRow) and adjacentInfo["column"] == (aColumn):
adjacentButton = ADJACENT INFORMATION
if endButtonInfo["row"] == (aRow + y) and endButtonInfo["column"] == (aColumn+x):
if originButton.cget("bg") == "black":
adjacentButton.configure (bg = "white")
else:
adjacentButton.configure (bg = "black")
### Function to find button position ###
def find_position(frame, row, column):
for children in frame.children.values():
info = children.grid_info()
if info["row"] == row and info["column"] == column:
return info
break
### Creating the window ###
othello = Tk()
othello.title("Othello Draft 1")
othello.geometry("800x800")
### Creating buttons ###
for r in range (8): #Rows
for c in range(8): #Columns
button = Button(othello, width = 10, height = 5)
button.grid(row = r, column = c)
button.configure (bg = "green", command = lambda buttonName = button, r = r, c = c: changeColour(buttonName, r, c))
### Running the window ###
othello.mainloop()
You could add the buttons to a list and use an if and elif statement to configure the buttons and input your conditions into the if.
for button in [list your buttons here]
if condition:
button.config(command=command(), bg=colour)
elif condition:
button.config(command=command2(), bg=colour2)

How to access through all the entry boxes and make them blank

As a new python learner, I was trying to create a form in Tkinter with some entry boxes which takes some values from a user. For that I have used For loop to create a 4x2 matrix of entry boxes and filled them with some dummy names.
Now I was wondering how to make all these boxes blank in one shot. The function that I created only makes last entry box blank. I am trying access through all the boxes one by one to make them blank but not able to do.
from tkinter import *
master = Tk()
master.geometry("175x175")
def clear():
e1.delete(0, END)
for y in range(4):
for i in range(2):
e1 = Entry(master)
e1.grid(row = y, column = i, padx = 20, pady= 10)
if y == 0:
if i == 0:
e1.insert(0,'Vishal')
else:
e1.insert(0,'Mishra')
elif y == 1:
if i == 0:
e1.insert(0,'ashish')
else:
e1.insert(0,'Mishra')
elif y == 2:
if i == 0:
e1.insert(0,'vikas')
else:
e1.insert(0,'Mishra')
else:
if i == 0:
e1.insert(0,'sacHin')
else:
e1.insert(0,'Mishra')
btn = Button(master, text = 'Clear', command = clear)
btn.grid(row= 4, column = 1)
master.mainloop()
please suggest..
you are only holding the last Entry you create, you will need to hold all of them. change your code like this:
entries = [] # note these changes
def clear():
for item in entries:
item.delete(0, END)
for y in range(4):
for i in range(2):
e1 = Entry(master)
entries.append(e1) # and this change
e1.grid(row = y, column = i, padx = 20, pady= 10)
if y == 0:
if i == 0:
e1.insert(0,'Vishal')
else:
e1.insert(0,'Mishra')
elif y == 1:
if i == 0:
e1.insert(0,'ashish')
else:
e1.insert(0,'Mishra')
elif y == 2:
if i == 0:
e1.insert(0,'vikas')
else:
e1.insert(0,'Mishra')
else:
if i == 0:
e1.insert(0,'sacHin')
else:
e1.insert(0,'Mishra')

How can I get my game of life code to animate in python?

I'm currently writing the John Conway's game of life in python and I'm stuck when it comes getting the cells to animate according to the rules. currently my code is compiling without any errors but I just can't figure out how I can get the code to animate. My code is:
code edit
from tkinter import *
from random import *
import time
import numpy as np
PIXEL_SIZE = 10
ROW = 910
COLUMN = 700
grid = []
updated_grid = [[]]
def create_grid():
for row in range(0, ROW):
grid2 = []
for column in range(0, COLUMN):
grid2.append(randint(0, 1))
grid.append(grid2)
def draw_grid():
for row in range(0, ROW):
for column in range(0, COLUMN):
if grid[row][column] == 1:
x0 = row*PIXEL_SIZE
y0 = column*PIXEL_SIZE
x1 = x0+PIXEL_SIZE
y1 = y0+PIXEL_SIZE
canvas.create_rectangle(x0, y0, x1, y1, fill='red')
def apply_rules():
for row in range(1, ROW - 1):
for column in range(1, COLUMN - 1):
neighbours_count = 0
# will count the neighbours for each cell
neighbours_count += grid[row-1][column-1] # top left
neighbours_count += grid[row][column-1] # top center
neighbours_count += grid[row+1][column-1] # top right
neighbours_count += grid[row-1][column] # middle left
neighbours_count += grid[row+1][column] # middle right
neighbours_count += grid[row-1][column+1] # bottom left
neighbours_count += grid[row][column+1] # bottom center
neighbours_count += grid[row+1][column+1] # bottom right
# Game Of Life rules:
# alive cell rules
if grid[row][column] == 1:
if neighbours_count < 2: # rule 1 any live cell with fewer than two live neighbours dies, as if by underpopulation
grid[row][column] = 0
elif neighbours_count == 2 | neighbours_count == 3: # rule 2 any live cell with two or three live neighbours lives on to the next generation
grid[row][column] = 1
elif neighbours_count > 3 & neighbours_count <= 8: # rule 3 any live cell with more than three live neighbours dies, as if by overpopulation
grid[row][column] = 0
else:
grid[row][column] = 0
elif grid[row][column] == 0: # dead cells rule 4 any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction
if neighbours_count == 3:
grid[row][column] = 1
else:
grid[row][column] = 0
def one_cycle():
apply_rules()
draw_grid()
window.after(1, one_cycle)
window = Tk() # creates the window for the game
window.title('Game Of Life Python') # is the game title written on the window
canvas_frame = Frame(window) # creates a frame on the window to hold the canvas
game_title = Frame(window) # creates a frame on the window to display the game title (which will be a label)
start_button = Button(window, text='Start Game', command=one_cycle) # creates a button which will be used to start the game
canvas = Canvas(canvas_frame, width=ROW, height=COLUMN, background='black') # creates the canvas used to the draw the game of life
game_title_label = Label(game_title, text='Game Of Life', font='Helvetica 20 bold', fg='grey') # creates the label for the game title which will be placed in a frame
canvas.grid(row=0, column=0) # places the canvas onto the canvas_frame
canvas_frame.grid(row=1, column=1) # places the canvas_frame onto the window
game_title_label.grid(rowspan=2, column=0) # places the title of the game onto the game_title frame
game_title.grid(row=0, columnspan=2) # places the frame for the game title onto the window
start_button.grid(rowspan=2, column=1) # places the start onto the window
create_grid()
window.mainloop()
I am new to python so please forgive me if you see any errors I've missed and thank you for any help you are able to give me.
I think you need a few modifications:
Change your Button to start the drawing: start_button = Button(window, text='Start Game', command=apply_rules)
Modify def apply_rules(): to have this addition at the end: window.after(0, apply_rules)
Don't call apply_rules() your self: apply_rules()
When you run the program you will need to press the Start Game button.
================
Update:
You may need to add another function to encapsulate the idea of running the rules and displaying the results continuously:
Keep def apply_rules(): as you have it in your posting and add a new function:
def one_cycle():
apply_rules()
draw_grid()
window.after(1, one_cycle) # use 1 to ease performance as Bryan suggests
Change the Button command to: command=one_cycle
Now you only need this at the bottom:
create_grid()
window.mainloop()

tkinter cant assign text variable

the problem was my input popup had to be a toplevel window so changing tk.Tk() to tk.Toplevel() makes it work fine ;)
#Josh Harrison
#3008088
from graphics import *
from random import randrange
import winsound, sys
#scale for size of squares
scale = 50
#setupBoard sets up the board with a randomly generated puzzle
def setupBoard(size, color):
board = [[[0, Rectangle(Point(scale*.05,scale*.05),Point(scale*.95,scale*.95))] for x in range(size)] for x in range(size)]
for x in range(size):
for y in range(size):
board[x][y][1] = Rectangle(Point(x*scale+scale*.05,y*scale+scale*.05),Point(x*scale+scale*.95,y*scale+scale*.95))
for i in range(1):
selectTile(board, Point(randrange(size)*scale,randrange(size)*scale), size, color)
return board
#selectTile does the action for selecting tiles
#set color to 0 for black and white and 1 for color rotation
def selectTile(board,point,size,color):
#sets value switch according to if colors are desired or not
if color == 1:
valueSwitch = colorSwitch
else:
valueSwitch = bwSwitch
x = int(point.getX()/scale)
y = int(point.getY()/scale)
#temp is made to preserve the selected tiles state
temp = board[x][y][0]
#swap all square values
#note try and except are also looped
for i in range(3):
for z in range(3):
try:
board[x-1+i][y-1+z][0] = valueSwitch(board[x-1+i][y-1+z][0])
except:
#overlap fix for x maxed
if x == size - 1 and y != size - 1:
board[0][y-1+z][0] = valueSwitch(board[0][y-1+z][0])
#overlap fix for y maxed
if y == size - 1 and x != size - 1:
board[x-1+i][0][0] = valueSwitch(board[x-1+i][0][0])
#overlap fix for bottom right corner
if x == size - 1 and y == size - 1:
board[0][0][0] = valueSwitch(board[0][0][0])
for a in range(2):
board[0][size-a-1][0] = valueSwitch(board[0][size-a-1][0])
board[size-a-1][0][0] = valueSwitch(board[size-a-1][0][0])
#give middle square initial value again
board[x][y][0] = temp
#updateBoard updates the squares to the right colour according to value
def updateBoard(board, size, count):
if count != 0:
winsound.Beep(333, 200)
for x in range(size):
for y in range(size):
if board[x][y][0] == 0:
board[x][y][1].setFill('white')
elif board[x][y][0] == 1:
board[x][y][1].setFill('yellow')
elif board[x][y][0] == 2:
board[x][y][1].setFill('green')
elif board[x][y][0] == 3:
board[x][y][1].setFill('blue')
elif board[x][y][0] == 4:
board[x][y][1].setFill('black')
#drawBoard draws the initial board
def drawBoard(size, board, win):
for x in range(size):
for y in range(size):
board[x][y][1].draw(win)
return
#checks to see if board is white(Winning condition)
def winGame(board, size):
#steps through all x and y values
for x in range(size):
for y in range(size):
if board[x][y][0] != 0:
return 0
#returns true if no black squares are found
return 1
#valueSwitch() just makes switching values easier by checking values and selecting the appropriate one
def colorSwitch(value):
if value == 4:
return 0
else:
return value + 1
#bwSwitch only selects from black and white value
def bwSwitch(value):
if value == 4:
return 0
else:
return 4
#winMessage() displaying a winning message graphic
def winMessage(size, scale, win):
gameMessage = Text(Point(size*scale/2,size*scale/2),"You have won logic!")
gameMessage.setSize(int(scale/4))
gameMessage.setTextColor('red')
gameMessage.draw(win)
#gameMenu() is a menu to select game size
def gameMenu():
win = GraphWin("Logic Menu", 400, 600)
win.setBackground('light blue')
board = [[[Text(Point(0,0),'bleh'),Rectangle(Point(0,0),Point(200,200))] for y in range(3)] for x in range(2)]
#Making and drawing the buttons ;)
for x in range(2):
for y in range(3):
board[x][y][1] = Rectangle(Point(x*200+200*.05,y*200+200*.05),Point(x*200+200*.95,y*200+200*.95))
board[x][y][1].draw(win)
board[0][0][0] = Text(board[0][0][1].getCenter(), 'Click for 5x5 puzzle')
board[1][0][0] = Text(board[1][0][1].getCenter(), 'Click for 7x7 puzzle')
board[0][1][0] = Text(board[0][1][1].getCenter(), 'Click for 9x9 puzzle')
board[1][1][0] = Text(board[1][1][1].getCenter(), 'Click for 12x12 puzzle')
board[0][2][0] = Text(board[0][2][1].getCenter(), 'Click to toggle colors')
board[1][2][0] = Text(board[1][2][1].getCenter(), 'Highscores!')
#drawing button options
for x in range(2):
for y in range(3):
board[x][y][0].draw(win)
#check to see what button is pressed
point = win.getMouse()
x = int(point.getX()/200)
y = int(point.getY()/200)
#colors is either 1 for colors or 0 for no colors
colors = 0
#turning colors on and off
#board[0][2][1] is the rectangle for colors
while y == 2:
if x == 0:
if colors == 0:
winsound.Beep(400, 200)
colors = 1
board[0][2][1].setFill('green')
else:
winsound.Beep(363, 200)
colors = 0
board[0][2][1].setFill('')
else:
winsound.Beep(400, 200)
board[1][2][1].setFill('red')
#board is just passed in for a smother button click effect not necessary for functionality
highscore_board(board)
point = win.getMouse()
x = int(point.getX()/200)
y = int(point.getY()/200)
board[x][y][1].setFill('red')
winsound.Beep(400, 200)
win.close()
if x == 0 and y == 0:
return 5 , colors
if x == 1 and y == 0:
return 7 , colors
if x == 0 and y == 1:
return 9 , colors
if x == 1 and y == 1:
return 12 , colors
return 5 , colors
#highscore() checks to see if player has highscore and outputs a highscore to a text file
def highscore(count):
#checks to see if highscore file exists
try:
scoreInfo = [line.strip() for line in open('highscore.txt')]
#remove all spacing
for i in range(scoreInfo.count('')):
scoreInfo.remove('')
scoreInfo[1]
scores = int(len(scoreInfo)/2)
newEntry = 0
#creates new highscore file is none exist
except:
win = GraphWin("Highscore!", 400, 200)
gameMessage = Text(Point(200,100),"Please input name: ")
gameMessage.setSize(int(scale/4))
gameMessage.setTextColor('red')
gameMessage.draw(win)
name=inputWin()
f = open('highscore.txt', 'w')
f.write(name)
f.write('\n'+str(count))
f.close()
gameMessage.setText(name+': '+str(count)+' - saved!')
time.sleep(1)
win.close()
return
#if there is a new highscore it is added at the beginning of the file
for i in range(scores):
if scores < 10 or count < int(scoreInfo[i*2+1]):
win = GraphWin("Highscore!", 400, 200)
gameMessage = Text(Point(200,100),"Please input name: ")
gameMessage.setSize(int(scale/4))
gameMessage.setTextColor('red')
gameMessage.draw(win)
name=inputWin()
f = open('highscore.txt', 'w')
#max 10 highscores 9 + new highscore
if scores >= 10:
scores = 9
for i in range(scores):
try:
if count < int(scoreInfo[i*2+1]) and not newEntry:
f.write(name)
f.write('\n'+str(count))
f.write('\n\n\n')
newEntry = 1
f.write(scoreInfo[i*2])
f.write('\n')
f.write(scoreInfo[i*2+1])
f.write('\n\n\n')
except:
pass
#if no entries have been added
#the new value is then added to the end
if newEntry == 0:
f.write(name)
f.write('\n'+str(count))
f.write('\n\n\n')
f.close()
gameMessage.setText(name+': '+str(count)+' - saved!')
time.sleep(1)
win.close()
break
pass
#board is just passed in for a smother button click effect not necessary for functionality
def highscore_board(board):
win = GraphWin("Highscores", 200, 500)
win.setBackground('light green')
try:
scoreInfo = [line.strip() for line in open('highscore.txt')]
#remove all spacing
for i in range(scoreInfo.count('')):
scoreInfo.remove('')
Text(Point(50,20),"Highscores:").draw(win)
for i in range(10):
Text(Point(10,45*i+60),str(i+1)+'. ').draw(win)
try:
Text(Point(60,45*i+60),scoreInfo[i*2]).draw(win)
Text(Point(170,45*i+60),scoreInfo[1+i*2]).draw(win)
except:
pass
except:
Text(Point(100,250),"no scores yet.").draw(win)
time.sleep(.05)
board[1][2][1].setFill('')
#prevent program crash if scoreboard is exited through os
try:
win.getMouse()
winsound.Beep(363, 200)
win.close()
except:
winsound.Beep(363, 200)
import tkinter as tk
def getString(ment,mGui):
global hsname
hsname = ment.get()
mGui.destroy()
mGui.quit()
def inputWin():
mGui = tk.Tk()
ment = tk.StringVar()
mGui.title('New Highscore!')
mEntry = tk.Entry(mGui,textvariable=ment).pack(side=tk.LEFT)
mbutton = tk.Button(mGui,text='OK',command=lambda:getString(ment,mGui),fg='red',bg='blue').pack(side=tk.RIGHT)
mGui.mainloop()
return hsname
this is the portion that wont work
import tkinter as tk
def getString(ment,mGui):
global hsname
hsname = ment.get()
mGui.destroy()
mGui.quit()
def inputWin():
mGui = tk.Tk()
ment = tk.StringVar()
mGui.title('New Highscore!')
mEntry = tk.Entry(mGui,textvariable=ment)
mEntry.pack(side=tk.LEFT)
mbutton = tk.Button(mGui,text='OK',command=lambda:getString(ment,mGui),fg='red',bg='blue')
mbutton.pack(side=tk.RIGHT)
mGui.mainloop()
return hsname
I'm just screwing around trying to make adding a highscore more visual for a game I made this code it works fine by itself but when I import it or even copy the whole code into a py file with other functions it just stops assigning ment any values I don't understand :/
any help is appreciated
this is the code that runs the game
#Josh Harrison
#3008088
from logic_game import *
def playGame():
option = gameMenu()
size = option[0]
color = option[1]
win = GraphWin("Logic Game", size*scale, size*scale)
win.setBackground('light pink')
board = setupBoard(size, color)
drawBoard(size, board, win)
countText = Text(Point(scale,scale/2),'moves: 0')
countText.setTextColor('red')
countText.draw(win)
count = 0
while not winGame(board, size):
updateBoard(board, size, count)
selectTile(board, win.getMouse(), size, color)
count += 1
countText.setText('moves: ' + str(count))
updateBoard(board, size, count)
winMessage(size, scale, win)
highscore(count)
#pauses the window and waits for click before continuing
win.getMouse()
#closes the window "win"
win.close()
playGame()
link for graphics.py
http://mcsp.wartburg.edu/zelle/python/graphics.py
I don't understand exactly what your problem is doing wrong, but I'm pretty sure I know what the problem is.
Most of your program is using some library named graphics to run a GUI. Then you're trying to use Tkinter to run another GUI in the same program.
I don't know what that graphics library that is, but unless it's either built on top of Tkinter, or specifically designed to work with Tkinter, this is unlikely to work. Both of them are going to try to be in charge of the one and only GUI for your program, handling all of the events from the user/windowing system, and so forth. One or both are going to fail.
In fact, even if graphics were built on top of Tkinter or designed to work together with it, calling mainloop on the Tkinter window is at best going to freeze up the rest of your GUI until you exit that mainloop, and at worst going to break the outer mainloop that the other GUI is relying on.
From what I can see from your other code, that graphics library seems to have enough features to do everything you were trying to do with Tkinter—create a new window, place some widgets on it, handle a button click. So, why not just use that?
Now that you've given us a link to the graphics library you're using… it looks like a thin wrapper around Tkinter. Which means you should be able to integrate them easily. You just have to create a new Toplevel instead of a root window (since graphics has already created a Tkinter root), and not call mainloop or quit (because you're already in a Tkinter main loop created by graphics).
Since you haven't given us an SSCCE that I can just run and hack on, I've built my own super-simple one around the first example in the graphics docs, which does what you were trying to do, and also shows how you can interact with the graphics window from the Tkinter code.
from graphics import *
import Tkinter as tk
def getString(ment,mGui):
global win
print(ment.get())
mGui.destroy()
win.close()
def inputWin():
global hsname
mGui = tk.Toplevel()
ment = tk.StringVar()
mGui.title('New Highscore!')
tk.Entry(mGui,textvariable=ment).pack(side=tk.LEFT)
tk.Button(mGui,text='OK',command=lambda:getString(ment,mGui),fg='red',bg='blue').pack(side=tk.RIGHT)
win.getMouse()
def main():
global win
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # Pause to view result
inputWin()
main()
It would be better to refactor this to eliminate your global variables, either using an OO design (create a class so you can store things as instance attributes) or a functional design (pass values through closures or bake them in with lambda/partial, as you're already doing in your Button command), but I tried to follow the style you already set in your code rather than rewrite everything.

Categories