我正在嘗試從 14 個專案的串列中創建一個包含 14 個單選按鈕的網格,我希望將按鈕排列成 7 對,到目前為止,我得到的是以下代碼:
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import *
root = tk.Tk()
root.geometry('400x400')
bs = ['Skin and Soft Tissue', 'Bone and Joint', 'Central Nervous System', 'Genito-
Urinary', 'Gastrointestinal', 'Cardiovascular', 'ENT', 'Gynaecological Infections',
'Intravascular access Device', 'Sexual Transmitted Infections', 'Pregancy Associated
Sepsis', 'Respiratory', 'Lyme Disease', 'Splenectomy/Functional Asplenia']
n = tk.StringVar()
nrows = 7
ncols = 2
nitems = 14
for r in range(nrows):
for c in range(ncols):
for body in range(len(bs)):
tk.Radiobutton(root, text = bs[r], var = n, value = bs[r]).grid(row =
r, column = c)
root.mainloop()
到目前為止我得到的是這個

我的問題是,如何讓 python 迭代串列中的每個專案,以便我獲得 7 對中的所有單選按鈕,它們都具有各自的名稱?
uj5u.com熱心網友回復:
嘗試這個
for r in range(nrows):
for c in range(ncols):
tk.Radiobutton(root, text = bs[r*ncols c], var = n, value = bs[r*ncols c]).grid(row = r, column = c)
它使用公式r*ncols c在bs串列中找到合適的專案。如果這不直觀,那么做一些計算來測驗它,例如
r c r*2 c
0 0 0
0 1 1
1 0 2
1 1 3
2 0 4
2 1 5
到目前為止,我得到的是:截圖
uj5u.com熱心網友回復:
以下是如何在設定的行和列中放置專案的示例:
import tkinter as tk
bs = ['Skin and Soft Tissue', 'Bone and Joint', 'Central Nervous System',
'Genito-Urinary', 'Gastrointestinal', 'Cardiovascular', 'ENT',
'Gynaecological Infections','Intravascular access Device',
'Sexual Transmitted Infections', 'Pregancy Associated Sepsis',
'Respiratory', 'Lyme Disease', 'Splenectomy/Functional Asplenia']
root = tk.Tk()
root.geometry('400x400')
n_rows = 7
n_cols = 2
n = tk.StringVar(value=' ')
for index, text in enumerate(bs):
c = index // n_rows
if c 1 > n_cols:
break
tk.Radiobutton(
root, text=text, var=n, value=text
).grid(row=index % n_rows, column=c, sticky='w')
root.mainloop()
首先請注意,此回圈對行進行優先級排序,即它首先填充所有行,然后再轉到下一列,并且如果專案多于n_cols * n_rows填充所有設定的行和列后會中斷。
基本上它使用索引來檢測專案索引和%(模)來設定行,因為它計算提醒然后例如第 6 個索引將回傳 6(按順序排列的第 7 行)和第 13 個索引(在這種情況下的最后一個專案)它將還回傳 6(再次按順序是第 7 行),因為這是除以 13 / 7 時的余數,這就是模回傳的結果。該列只是從按列劃分的索引基礎設定的,因此基本上它會在列被填滿時增加,因為例如第 7 個索引(串列中的第 8 個專案)將執行c = 7 // 71(第 2 列)然后 13 // 7 也是1 等。(我也建議使用,sticky='w'以便檢查按鈕在左側(或您需要的任何一側)對齊)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342465.html
上一篇:從串列中選擇n個關鍵字
