Кнопки Tkinter смешиваются друг с другом - PullRequest
0 голосов
/ 01 декабря 2019

Я не знаю, как это объяснить, но у меня есть две разные страницы, каждая с определенным количеством кнопок в виде сетки

Простая форма

Сложная форма

, но когда я выбираю одну из переключателей, затем выбираю другую после того, как она смешается

Хаос

Воткод для создания сетки

import tkinter as tk
from tkinter import filedialog, Text
import os
import time, sys
from time import sleep

root = tk.Tk()
root.geometry('700x700')
def changecolo(i, j):
    if not ((i == 0 and j == 0) or (i == 12 and j == 12)):
        if mFrame.grid_slaves(row = i, column = j)[0].cget('bg') == 'black':
            mFrame.grid_slaves(row = i, column = j)[0].configure(bg = 'white')
        elif mFrame.grid_slaves(row = i, column = j)[0].cget('bg') == 'white':
            mFrame.grid_slaves(row = i, column = j)[0].configure(bg = 'grey')
        elif mFrame.grid_slaves(row = i, column = j)[0].cget('bg') == 'grey':
            mFrame.grid_slaves(row = i, column = j)[0].configure(bg = 'black')
def setalg():
    value = 6
def makegrid6():
    mFrame.grid_forget()
    makegrid66()
def makegrid66():
    for i in range(6):
        for j in range (6):
            if i == 0 and j == 0:
                grids6 = tk.Button(mFrame, bg='blue', text = (5 - i) + (5 - j), state = 'disabled', highlightcolor="black", highlightthickness=1, width = 11, height = 5)
                grids6.grid(row = i, column = j)
            elif i == 5 and j == 5:
                grids6 = tk.Button(mFrame, bg='red', text = (5 - i) + (5 - j) , state = 'disabled',highlightcolor="black", highlightthickness=1, width = 11, height = 5)
                grids6.grid(row = i, column = j)
            elif (((i == 0 or i == 1 or i == 2) and (j == 2)) or (i == 4 and j == 1)):
                grids6 = tk.Button(mFrame, bg='white', text = (5 - i) + (5 - j) , highlightcolor="black", highlightthickness=1, width = 11, height = 5, state = 'disabled')
                grids6.grid(row = i, column = j)
            elif (i == 3 and j == 2):
                grids6 = tk.Button(mFrame, bg='grey', text = (5 - i) + (5 - j) , highlightcolor="black", highlightthickness=1, width = 11, height = 5, state = 'disabled')
                grids6.grid(row = i, column = j)
            else:
                grids6 = tk.Button(mFrame, bg='black', text = (5 - i) + (5 - j), fg = 'white', highlightcolor="black", highlightthickness=1, width = 11, height = 5, state = 'disabled')
                grids6.grid(row = i, column = j) 
    return mFrame.grid_slaves, i, j

def makegrid10():
    mFrame.grid_forget()
    makegrid100()
def makegrid100():
for i in range(13):
    for j in range (13):
        if i == 0 and j == 0:
            grids10 = tk.Button(mFrame, bg='blue', text = (12 - i) + (12 - j), fg = 'white', state = 'disabled', highlightcolor="black", highlightthickness=1, width = 4, height = 2, command=lambda x = i, y = j: changecolo(x, y))
            grids10.grid(row = i, column = j)
        elif i == 12 and j == 12:
            grids10 = tk.Button(mFrame, bg='red', text = (12 - i) + (12 - j), fg = 'white', state = 'disabled',highlightcolor="black", highlightthickness=1, width = 4, height = 2, command=lambda x = i, y = j: changecolo(x, y))
            grids10.grid(row = i, column = j)
        else:
            grids10 = tk.Button(mFrame, bg='black', text = (12 - i) + (12 - j), fg = 'white', highlightcolor="black", highlightthickness=1, width = 4, height = 2, command=lambda x = i, y = j: changecolo(x, y))
            grids10.grid(row = i, column = j)
return mFrame.grid_slaves, i, j   

def play():
   if diffVar.get() == "sim":
       butons, l, k = makegrid66()
       Greedy(butons, l, k)
   else:
       butons, l, k = makegrid100()
       Greedy(butons, l, k)
def aStar():
   print(1000010)

def Greedy(butons, k, l):
    print(k, l)

def UCS():
    print(99)
mFrame = tk.Frame(root, height = 500, width = 500, bg = "lightgrey")
mFrame.place(x= 10, y = 10)

diffVar = tk.StringVar()
dif = tk.Label(root, text = "Problem Difficulty", bg = "Lightgrey")
dif.place (x = 550, y = 30)

simp = tk.Radiobutton(root, text = "Simple", value = "sim", bg = "Lightgrey", variable = diffVar, command = makegrid6)
simp.place(x = 550, y = 60)
comp = tk.Radiobutton(root, text = "Complex", value = "com", bg = "Lightgrey", variable = diffVar, command = makegrid10)
comp.place(x = 550, y = 90)

algVar = tk.IntVar()
algVar.set(1)
dif = tk.Label(root, text = "Choose an Algorithm", bg = "Lightgrey")
dif.place (x = 550, y = 180)

alg1 = tk.Radiobutton(root, text = "A*", value = 1, bg = "Lightgrey", variable = algVar, command = setalg)
alg1.place(x = 550, y = 210)
alg2 = tk.Radiobutton(root, text = "Greedy", value = 2, bg = "Lightgrey", variable = algVar, command = setalg)
alg2.place(x = 550, y = 240)
alg3 = tk.Radiobutton(root, text = "UCS", value = 3, bg = "Lightgrey", variable = algVar, command = setalg)
alg3.place(x = 550, y = 270)

playbu = tk.Button(root, text = "Play", bg = "White", width = 15, command = play)
playbu.place(x = 10, y = 550)

nextbu = tk.Button(root, text = "Next", bg = "White", width = 15)
nextbu.place(x = 140, y = 550)

fasterbu = tk.Button(root, text = "Faster", bg = "White", width = 15)
fasterbu.place(x = 270, y = 550)

resetbu = tk.Button(root, text = "Reset", bg = "White", width = 15)
resetbu.place(x = 400, y = 550)



root.mainloop()

- это любой возможный способ, которым кнопки изменят свой размер так, чтобы они соответствовали размеру холста, без необходимости настройки ширины и высотыкнопка

1 Ответ

0 голосов
/ 01 декабря 2019

Сначала я использовал это, чтобы удалить старый кадр со всеми кнопками и создать новый кадр для новых кнопок

def makegrid6():
    global mFrame

    mFrame.destroy()

    mFrame = tk.Frame(root, height = 500, width = 500, bg = "lightgrey")
    mFrame.place(x= 10, y = 10)

    makegrid66()

, но у него была одна проблема - новый кадр был создан поверх других виджетов, а затем был скрыти недоступен.

Итак, я создал xFrame, в который я положил mFrame, и xFrame будет все время находиться в окне, поэтому он не будет перемещаться поверх других виджетов

root = tk.Tk()
root.geometry('700x700')

# parent `root` 
xFrame = tk.Frame(root, height = 500, width = 500, bg = "lightgrey")
xFrame.place(x= 10, y = 10)

# parent `xFrame`
mFrame = tk.Frame(xFrame, height = 500, width = 500, bg = "lightgrey")
mFrame.pack()

и затем он показывает новый кадр за checkbox и другими кнопками.

Чтобы поместить mFrame в xFrame, я использую pack() вместо place(), потому что он не нуждается в опциях и тамдругих виджетов не будет, поэтому нет необходимости устанавливать x,y.

Вы сказали, что положили mFrame в Canvas (но я не вижу его в коде), чтобы вы могли использовать Canvas вместо xFrame.


Кстати: есть предложение не использовать пробелы вокруг = внутри функций.
См. PEP 8 - Руководство по стилю для кода Python .


Здесь код с xFrame

Я также изменил makegrid100(), чтобы сделать его короче и более читабельным.

import tkinter as tk
from tkinter import filedialog, Text
import os
import time, sys
from time import sleep

# --- functions ---

def changecolo(i, j):
    if not ((i == 0 and j == 0) or (i == 12 and j == 12)):
        if mFrame.grid_slaves(row=i, column=j)[0].cget('bg') == 'black':
            mFrame.grid_slaves(row=i, column=j)[0].configure(bg='white')
        elif mFrame.grid_slaves(row=i, column=j)[0].cget('bg') == 'white':
            mFrame.grid_slaves(row=i, column=j)[0].configure(bg='grey')
        elif mFrame.grid_slaves(row=i, column=j)[0].cget('bg') == 'grey':
            mFrame.grid_slaves(row=i, column=j)[0].configure(bg='black')

def setalg():
    value = 6

def makegrid6():
    global mFrame # inform function to use external/global variable instead of locla one when it will assign value (`=`) 

    mFrame.destroy()

    mFrame = tk.Frame(xFrame, height=500, width=500, bg="lightgrey")
    mFrame.pack()

    makegrid66()

def makegrid66():

    for i in range(6):
        for j in range (6):
            if i == 0 and j == 0:
                grids6=tk.Button(mFrame, bg='blue', text=(5 - i) + (5 - j), state='disabled', highlightcolor="black", highlightthickness=1, width=11, height=5)
                grids6.grid(row=i, column=j)
            elif i == 5 and j == 5:
                grids6=tk.Button(mFrame, bg='red', text=(5 - i) + (5 - j) , state='disabled', highlightcolor="black", highlightthickness=1, width=11, height=5)
                grids6.grid(row=i, column=j)
            elif (((i == 0 or i == 1 or i == 2) and (j == 2)) or (i == 4 and j == 1)):
                grids6=tk.Button(mFrame, bg='white', text=(5 - i) + (5 - j) , highlightcolor="black", highlightthickness=1, width=11, height=5, state='disabled')
                grids6.grid(row=i, column=j)
            elif (i == 3 and j == 2):
                grids6=tk.Button(mFrame, bg='grey', text=(5 - i) + (5 - j) , highlightcolor="black", highlightthickness=1, width=11, height=5, state='disabled')
                grids6.grid(row=i, column=j)
            else:
                grids6=tk.Button(mFrame, bg='black', text=(5 - i) + (5 - j), fg='white', highlightcolor="black", highlightthickness=1, width=11, height=5, state='disabled')
                grids6.grid(row=i, column=j) 
    return mFrame.grid_slaves, i, j

def makegrid10():
    global mFrame # inform function to use external/global variable instead of locla one when it will assign value (`=`) 

    mFrame.destroy()

    mFrame = tk.Frame(xFrame, height=500, width=500, bg="lightgrey")
    mFrame.pack()

    makegrid100()

def makegrid100():

    for i in range(13):
        for j in range (13):
            if i == 0 and j == 0:
                bg_color = 'blue'
                state = 'disabled'
            elif i == 12 and j == 12:
                bg_color = 'red'
                state = 'disabled'
            else:
                bg_color = 'black'
                state = 'normal'

            b = tk.Button(mFrame, bg=bg_color, text=(12-i)+(12-j), state=state, fg='white', highlightcolor="black", highlightthickness=1, width=4, height=2, command=lambda x=i, y=j: changecolo(x, y))
            b.grid(row=i, column=j)

    return mFrame.grid_slaves, i, j   

def play():
   if diffVar.get() == "sim":
       butons, l, k=makegrid66()
       Greedy(butons, l, k)
   else:
       butons, l, k=makegrid100()
       Greedy(butons, l, k)
def aStar():
   print(1000010)

def Greedy(butons, k, l):
    for i in range(k + 1):
        for j in range(l + 1):
            print(i, j)
            mini=butons(row=i, column=j)[0].cget('text')
            m, n=i, j
            if i - 1 > -1:
                if butons(row=i - 1, column=j)[0].cget('text') < mini:
                    mini=butons(row=i - 1, column=j)[0].cget('text')
                    m=i - 1
            if i + 1 < 6:
                if butons(row=i + 1, column=j)[0].cget('text') < mini:
                    mini=butons(row=i + 1, column=j)[0].cget('text')
                    m=i + 1
            if j - 1 > -1:
                if butons(row=i, column=j - 1)[0].cget('text') < mini:
                    mini=butons(row=i, column=j - 1)[0].cget('text')
                    n=j - 1
            if j + 1 < 6:
                if butons(row=i, column=j + 1)[0].cget('text') < mini:
                    mini=butons(row=i, column=j + 1)[0].cget('text')
                    n=j + 1
            i, j=m, n
            butons(row=m, column=n)[0].configure(bg='brown')

def UCS():
   print(99)

# --- main ---

root = tk.Tk()
root.geometry('700x700')

xFrame = tk.Frame(root, height=500, width=500, bg="lightgrey")
xFrame.place(x= 10, y=10)

mFrame = tk.Frame(xFrame, height=500, width=500, bg="lightgrey")
mFrame.pack()

diffVar = tk.StringVar()
dif = tk.Label(root, text="Problem Difficulty", bg="Lightgrey")
dif.place (x=550, y=30)

simp = tk.Radiobutton(root, text="Simple", value="sim", bg="Lightgrey", variable=diffVar, command=makegrid6)
simp.place(x=550, y=60)
comp = tk.Radiobutton(root, text="Complex", value="com", bg="Lightgrey", variable=diffVar, command=makegrid10)
comp.place(x=550, y=90)

algVar = tk.IntVar()
algVar.set(1)
dif = tk.Label(root, text="Choose an Algorithm", bg="Lightgrey")
dif.place (x=550, y=180)

alg1 = tk.Radiobutton(root, text="A*", value=1, bg="Lightgrey", variable=algVar, command=setalg)
alg1.place(x=550, y=210)
alg2 = tk.Radiobutton(root, text="Greedy", value=2, bg="Lightgrey", variable=algVar, command=setalg)
alg2.place(x=550, y=240)
alg3 = tk.Radiobutton(root, text="UCS", value=3, bg="Lightgrey", variable=algVar, command=setalg)
alg3.place(x=550, y=270)

f2 = tk.Canvas(root, height=30, width=30, bg="White")

playbu = tk.Button(root, text="Play", bg="White", width=15, command=play)
playbu.place(x=10, y=550)

nextbu = tk.Button(root, text="Next", bg="White", width=15)
nextbu.place(x=140, y=550)

fasterbu = tk.Button(root, text="Faster", bg="White", width=15)
fasterbu.place(x=270, y=550)

resetbu = tk.Button(root, text="Reset", bg="White", width=15)
resetbu.place(x=400, y=550)

root.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...